Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top