0

This is not a duplicate of Locking a file in Python

I have two scripts, one runs every 30 minutes, the other one runs every one minute. and they both use the same file to do few things.

at some point, every 30 minute they try to access the same file at the same time and they corrupt the file. I was thinking about using wait. but they are two independent scripts and I am not sure if this is possible.

Any idea?

I thought about using

    with FileLock("document.txt")

The problem that arise is; if script-1 acquire the lock for "document.txt" then script-2 wants to access document.txt, is it going to wait that script-1 finish? or is it going to skip that line of code? as the 2nd one isn't an option? also. once the lock is acquired, how to remove it when it's no longer needed?

  • Your **writer** (30 minute script) should **replace** the file instead of **overwriting** it. Then there's no need to synchronise **reader** with the update. – Dima Tisnek Aug 22 '19 at 01:32

1 Answers1

0

One of the simpliest ways to get this done (in case you have write access to the file's directory) is to create an additional file (like filename.lck) to point out that some script is working on that file. Obviously, once a script has finished working with the file, that lock-file needs to be removed.

But honestly, I would be very surprised if such a locking mechanism is not foreseen in Python. How exactly do you open and close the mentioned file? Maybe some parameter already takes care of the locking.

Dominique
  • 16,450
  • 15
  • 56
  • 112