在 Python 中锁定文件 [英] Locking a file in Python

查看:59
本文介绍了在 Python 中锁定文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要锁定一个文件以便在 Python 中写入.它将一次从多个 Python 进程访问.我在网上找到了一些解决方案,但大多数都无法达到我的目的,因为它们通常仅基于 Unix 或基于 Windows.

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 they are often only Unix based or Windows based.

推荐答案

好吧,所以我最终使用了我编写的代码 这里,在我的网站上 链接已失效,请查看archive.org(也可在 GitHub 上找到).我可以按以下方式使用它:

Alright, so I ended up going with the code I wrote here, on my website link is dead, view on archive.org (also available on GitHub). I can use it in the following fashion:

from filelock import FileLock

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

这篇关于在 Python 中锁定文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆