kartheek7895
kartheek7895

Reputation: 351

Pythonic way to handle if the file being written is deleted externally

A python process is writing to a file and the file has been deleted/moved by an external process (cron job in my case).

The python process will continue to execute without any errors (expected as it is being written to the buffer rather than the file and will be flushed after f.close()). Yet there won't be any new file created in this case and buffer will be silently discarded(correct me if I'm wrong).

Is there any pythonic way to handle this instead of checking if file exists and create one if not, before every write operation.

Upvotes: 4

Views: 393

Answers (1)

Kurtis Rader
Kurtis Rader

Reputation: 7459

There is no "pythonic" way to do this because the question isn't about a specific language. It's an operating system question. So the answer is going to be different for MS Windows than it is for a UNIX like OS such as Linux or macOS. To do this efficiently requires using a facility such as the Linux inotify API. A simpler approach that will work on any UNIX like OS is to open the file then call os.fstat() and remember the st_ino member of the returned object. Then periodically call os.stat() on the path name and compare its st_ino value to the one you saved earlier. If it changes, or the os.stat() call fails, then you know the file name you are writing to is no longer the same file.

Upvotes: 1

Related Questions