防止文件被打开

发布于 2024-10-08 00:01:36 字数 337 浏览 2 评论 0原文

我正在编写一个 Python 记录器脚本,它按以下方式写入 CSV 文件:

  1. 打开文件
  2. 追加数据
  3. 保存更改所必需的,以便在每次记录例程后确保安全。)

关闭文件(我认为这是 :
该文件可以通过 Windows 资源管理器轻松访问(我使用的是 XP)。如果文件在 Excel 中打开,则对该文件的访问将被 Excel 锁定。当脚本尝试附加数据时,显然它失败了,然后它完全中止。

目标:
有没有一种方法可以使用 Python 锁定文件,以便对它的任何访问都保持为脚本独占?或者也许我的方法一开始就很糟糕?

I am writing a Python logger script which writes to a CSV file in the following manner:

  1. Open the file
  2. Append data
  3. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

这样的小城市 2024-10-15 00:01:37

无需在每次访问后关闭并重新打开文件,只需刷新其缓冲区即可:

theloggingfile.flush()

这样,您可以保持文件打开以在 Python 中进行写入,这应该会锁定该文件,防止其他程序打开该文件进行写入。我认为当它在 Python 中打开时,Excel 将能够以只读方式打开它,但如果不重新启动到 Windows,我无法检查它。

编辑:我认为您不需要以下步骤。 .flush() 应将其发送到操作系统,如果您尝试在另一个程序中查看它,操作系统应为其提供缓存版本。使用 os.fsync 强制操作系统将其真正写入硬盘,例如,如果您担心突然断电。

os.fsync(theloggingfile.fileno())

Rather than closing and reopening the file after each access, just flush its buffer:

theloggingfile.flush()

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. Use os.fsync to force the OS to really write it to the hard drive, e.g. if you're concerned about sudden power failures.

os.fsync(theloggingfile.fileno())
撩心不撩汉 2024-10-15 00:01:37

据我所知,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文