Home > Mobile >  Never-ending file existence check loop
Never-ending file existence check loop

Time:06-23

I'm sorry, I'm a complete beginner but very fascinated by scripting automation. I'm trying to check for the existence of a file that arrives once in a while. I want to read it and then delete it. I can't figure out how to keep this action running without the goto Label feature. Can anyone advise me please?

import os
import os.path
import time

path = os.path.exists('file.txt')

#loop
if path is True:
    print("File exists.")
    time.sleep(1)
    os.remove("file.txt")  # Remove the file.
# Now I need to start the loop again.
else:
    print("File doesn't exist")
    time.sleep(1)
# Now I need to start the loop again.
# And keep it running forever.

CodePudding user response:

This is what "while" loops are for.

import os.path
import time

while True:
    time.sleep(1)
    if os.path.exists('file.txt'):
        print("File exists.")
        os.remove("file.txt")          #remove the file.
    else:
        print("File doesn't exist")

You can do this with a batch file. You don't need Python.

CodePudding user response:

I think what you are looking for is a folder monitor which performs actions based on the event handling in the folder. I recommend using the 'watchdog' library in python to monitor the folder for incoming or outgoing files while the 'subprocess' library executes actions like reading and deleting. Refer to the code below

Code:

import subprocess
import time
import os

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

def on_created(event):
    print("A File is arrived",os.path.basename(event.src_path))
    time.sleep(10)
    os.remove(event.src_path)

def on_deleted(event):
    print("File Deleted")

if __name__ == "__main__":

    event_handler= FileSystemEventHandler()

    event_handler.on_created=on_created
    event_handler.on_deleted=on_deleted

    path="A:/foldername" #"Enter the folder path" you want to monitor here

    observer= Observer()
    observer.schedule(event_handler,path,recursive=False)  #If recursive is set to be True it will check in the subdirectories for contents if a folder is added to our path
    observer.start()

    try:
        while True:
            time.sleep(15)  # Sleeps for 15 seconds
    except KeyboardInterrupt:
        observer.stop()   # The code terminates if we hit any key in the folder or else it keeps running for ever
    observer.join()
    

Also, if you want to read the file before deleting then add the file reading code in the on_created method before "os.remove" and the code should work fine for you now!

  • Related