Threadsafe and fault-tolerant file writes

后端 未结 4 1797
傲寒
傲寒 2020-12-06 06:57

I have a long-running process which writes a lot of stuff in a file. The result should be everything or nothing, so I\'m writing to a temporary file and rename it to the rea

4条回答
  •  萌比男神i
    2020-12-06 07:11

    You could use the lockfile module to lock the file while you are writing to it. Any subsequent attempt to lock it will block until the lock from the previous process/thread has been released.

    from lockfile import FileLock
    with FileLock(filename):
        #open your file here....
    

    This way, you circumvent your concurrency issues and do not have to clean up any leftover file if an exception occurs.

提交回复
热议问题