开发者

Prevent a file from being opened

开发者 https://www.devze.com 2023-01-30 01:53 出处:网络
I am writing a Python logger script which writes to a CSV file in the following manner: Open the file Append data

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 ope开发者_开发问答ned 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?


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())


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消