Skip to content
Advertisement

How to accurately check folders or files in python

I’ve been trying to code something that helps me make a file whenever it got deleted.

My code:

import os
from os.path import exists
from time import time, sleep


#Variable
check_folder = exists(#path)


def checkfilepy():
    if check_folder:
        print('ClientSettings have already existed!')
    else:
        create_folder = os.makedirs(#path)
        print('Successfully created ClientSettings!')

        #Variable
        check_file = exists(#path)

        #If statement
        if check_file:
            print('file have already existed!')
        else:
            create_file = open(#path, 'x')
            create_file.write(#write stuff in)
            print('Successfully created file')

while True:
    sleep(60 - time() % 60)
    cfp = checkfilepy() 

Do you guys have any ideas to continuously check if the file is still there?

Advertisement

Answer

Like Sayse, I would prefer to only check when needed. But if you *really* want to check regularly, you can use the threading library :

import threading
import time

def frequent_check():
    while True:
        checkfilepy()
        time.sleep(60 - time.time() % 60)


if __name__ == '__main__':
    t = threading.Thread(target=frequent_check)
    t.run()
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement