Locking a file in Python

后端 未结 13 2393
悲&欢浪女
悲&欢浪女 2020-11-22 03:00

I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as

13条回答
  •  长发绾君心
    2020-11-22 03:52

    To add on to Evan Fossmark's answer, here's an example of how to use filelock:

    from filelock import FileLock
    
    lockfile = r"c:\scr.txt"
    lock = FileLock(lockfile + ".lock")
    with lock:
        file = open(path, "w")
        file.write("123")
        file.close()
    

    Any code within the with lock: block is thread-safe, meaning that it will be finished before another process has access to the file.

提交回复
热议问题