1

I would like to safely open and write to a file, so I decided to use the fileLock python library. This is my code:

            with filelock.FileLock('../rsc/datasets/train/' + server_predict.remove_special_chars(str(id_park)) + '.csv'):
                with open('../rsc/datasets/train/' + server_predict.remove_special_chars(str(id_park)) + '.csv', mode='a') as file:
                    for line in data_by_id.values:
                        a = "\"" + server_predict.remove_special_chars(str(line[0])) + "\",\"" + str(line[1]) + "\"," + str(line[2]) #+ "\n"
                        file.write(a)

However, this raises a PermissionError exception, sometimes on the

file.write(a)

line and others in the line

for line in data_by_id.values

Any clue where this error might come from? Is it me that I do not understand how fileLock works??

Thanks!

1 Answers1

1

You need to create a separate lock-file like shown here:

from filelock import Timeout, FileLock

lock = FileLock("high_ground.txt.lock")
with lock:
    open("high_ground.txt", "a").write("You were the chosen one.")

Don't use a FileLock to lock the file you want to write to, instead create a separate .lock file as shown above.

Note the .lock extension for the FileLock.

Community
  • 1
  • 1
Darkonaut
  • 20,186
  • 7
  • 54
  • 65