![]() |
How to check if a file has finished being written - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to check if a file has finished being written (/thread-33303.html) |
How to check if a file has finished being written - leocsmith - Apr-14-2021 I have a programme that writes an mtx file to a specified directory on my laptop. It's a very large file (~400,000 KB) and so takes quite some time to finish being written. The next block in my code is dependent on the mtx file being fully written but proceeds to execute once the mtx file first appears in the directory. I had used: time.sleep(120)between the two blocks to ensure the file was fully written, but I want a more robust way of checking as this sleep time may not always work. Any ideas on how to check that the file has finished being written? I've had a look at the watchdog module but I can't wrap my head around the syntax. Thank you. RE: How to check if a file has finished being written - snippsat - Apr-14-2021 Can check size of file and time.sleep() alone should not be used,better to use schedule either from OS or eg libraries like schedule, APScheduler. Example. import schedule, time from pathlib import Path def check_file(): file = Path('somefile.cfg') if file.exists() and file.stat().st_size >= 75: print('File is ok') else: print('File not ok') schedule.every(30).seconds.do(check_file) while True: schedule.run_pending() time.sleep(1)Now most file exists and be at least equal to 75kb or larger. Test run after a minute i delete some from the file,the status should change.
RE: How to check if a file has finished being written - perfringo - Apr-14-2021 There is also built-in fcntl — The fcntl and ioctl system calls which contains fcntl.lockf(fd, cmd, len=0, start=0, whence=0). It should be possible to lock file until writing has finished. |