Search code examples
pythonloggingfile-locking

Prevent a file from being opened


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?


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