Python multiple threads accessing same file

后端 未结 3 1185
小蘑菇
小蘑菇 2021-01-04 05:52

I have two threads, one which writes to a file, and another which periodically moves the file to a different location. The writes always calls open before writi

3条回答
  •  时光说笑
    2021-01-04 06:25

    Check out http://www.evanfosmark.com/2009/01/cross-platform-file-locking-support-in-python/

    You can use a simple lock with his code, as written by Evan Fosmark in an older StackOverflow question:

    from filelock import FileLock
    
    with FileLock("myfile.txt"):
        # work with the file as it is now locked
        print("Lock acquired.")
    

    One of the more elegant libraries I've ever seen.

提交回复
热议问题