防止文件被打开
我正在编写一个 Python 记录器脚本,它按以下方式写入 CSV 文件:
- 打开文件
- 追加数据
- 保存更改所必需的,以便在每次记录例程后确保安全。)
关闭文件(我认为这是 :
该文件可以通过 Windows 资源管理器轻松访问(我使用的是 XP)。如果文件在 Excel 中打开,则对该文件的访问将被 Excel 锁定。当脚本尝试附加数据时,显然它失败了,然后它完全中止。
目标:
有没有一种方法可以使用 Python 锁定文件,以便对它的任何访问都保持为脚本独占?或者也许我的方法一开始就很糟糕?
I am writing a Python logger script which writes to a CSV file in the following manner:
- Open the file
- Append data
- Close the file (I think this is necessary to save the changes, to be safe after every logging routine.)
PROBLEM:
The file is very much accessible through Windows Explorer (I'm using XP). If the file is opened in Excel, access to it is locked by Excel. When the script tries to append data, obviously it fails, then it aborts altogether.
OBJECTIVE:
Is there a way to lock a file using Python so that any access to it remains exclusive to the script? Or perhaps my methodology is poor in the first place?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无需在每次访问后关闭并重新打开文件,只需刷新其缓冲区即可:
这样,您可以保持文件打开以在 Python 中进行写入,这应该会锁定该文件,防止其他程序打开该文件进行写入。我认为当它在 Python 中打开时,Excel 将能够以只读方式打开它,但如果不重新启动到 Windows,我无法检查它。
编辑:我认为您不需要以下步骤。
.flush()
应将其发送到操作系统,如果您尝试在另一个程序中查看它,操作系统应为其提供缓存版本。使用 os.fsync 强制操作系统将其真正写入硬盘,例如,如果您担心突然断电。Rather than closing and reopening the file after each access, just flush its buffer:
This way, you keep it open for writing in Python, which should lock the file from other programs opening it for writing. I think Excel will be able to open it as read-only while it's open in Python, but I can't check that without rebooting into Windows.
EDIT: I don't think you need the step below.
.flush()
should send it to the operating system, and if you try to look at it in another program, the OS should give it the cached version. Useos.fsync
to force the OS to really write it to the hard drive, e.g. if you're concerned about sudden power failures.据我所知,Windows不支持文件锁定。换句话说,无法阻止不知道您的文件被锁定的应用程序读取文件。
但剩下的问题是:Excel 如何实现这一点?
您可能想先尝试写入临时文件(Excel 不知道的文件),然后用它替换原始文件。
As far as I know, Windows does not support file locking. In other words, applications that don't know about your file being locked can't be prevented from reading a file.
But the remaining question is: how can Excel accomplish this?
You might want to try to write to a temporary file first (one that Excel does not know about) and replace the original file by it lateron.