在 python 中使用锁定文件后写入文件时出现 PermissionError [Errno 13]

PermissionError [Errno 13] when writing to a file after using lockfile in python

我想安全地打开和写入文件,所以我决定使用 fileLock python 库。这是我的代码:

            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)

但是,这会引发 PermissionError 异常,有时会在

file.write(a)

行和行中的其他人

for line in data_by_id.values

知道这个错误可能来自哪里吗?是我不懂fileLock的原理吗??

谢谢!

您需要创建一个单独的锁定文件,如图所示 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.

请注意 FileLock.lock 扩展名。