Read CSV - The process cannot access the file

Lets go, all these strange “bool = whatever” phrases i used are not neccessary because python already has a function for this:

While True:

So i can start my While loop for reading a CSV like:

while True:
	try:
		with io.open(SlogFilePath,"r", encoding="utf-16(LE)") as SlogFile:
			SLOG = SlogFile.read().splitlines()

This will now run forever because it´s not really a condition and so always true.
To handle a failing attempt we need to use an except statement. Because i know i want to handle a Windows Error i can define the error like this:

while True:
	try:
		with io.open(SlogFilePath,"r", encoding="utf-16(LE)") as SlogFile:
			SLOG = SlogFile.read().splitlines()
    except OSError:
        time.sleep(0.5)

Now this loop will run again and again even if there is a file access error.

To get an output if the reading works we need to add an else statement.

while True:
	try:
		with io.open(SlogFilePath,"r", encoding="utf-16(LE)") as SlogFile:
			SLOG = SlogFile.read().splitlines()
    except OSError:
        time.sleep(0.5)
    else:
        return SLOG

So the exception handles what happens if we encounter an error, the else statement handles what happens if there is no error.
We add a maximum amount of retries to be save. After the max amount is reached, we raise the error, even if there is none.

def Read_SLOG():
    retry = 0
    max_retries=5
    while True:
        try:
            with io.open(SlogFilePath,"r", encoding="utf-16(LE)") as SlogFile:
                SLOG = SlogFile.read().splitlines()
        except OSError:
            time.sleep(0.5)
            retry += 1
            if retry > max_retries:
                raise
        else:
            return SLOG

Similar procedure for writing:

def Write_QLOG_START_Entry():
	retry = 0
	max_retries=5
	while True:
		try:
			with io.open(QlogFilePath,"w", encoding = "UTF8", newline='') as Qlogfile:	
				for Qlog in QLOG_START_New:
					writer = csv.writer(Qlogfile,delimiter="'")
					writer.writerow([Qlog])
		except OSError:
			time.sleep(0.5)
			retry += 1
			if retry > max_retries:
				raise
		else:
			return QLOG_START_New_Entry

More Info:

What Are Try/Except Statements in Python? | by Jonathan Hsu | Better Programming
8. Errors and Exceptions — Python 3.11.0 documentation

2 Likes