Check if any file is existing else do the command

Viewed 68

I'm given a task to detect if there is a file inside a path, if there is no file then sleep and wait until there is a file existing else do the command.

Here is my code

import os,time

path = 'C:\\Users\\test'
for dir, sub_dirs, files in os.walk(path):
    while not files:
        print("no files at this level")
        time.sleep(1)
    if files:
        print("file detected")

Even I put the file inside the path, it keeps sleeping, it does not print file detected, What is wrong with this?

2 Answers

files won't change in the while loop. You'll have to os.walk again.

import os,time

def file_exists(path):
    for dir, sub_dirs, files in os.walk(path):
        return files

path = r'C:\Users\test'
while True:
    if file_exists(path):
        print("file detected")
        break
    else:
        print("no files at this level")
        time.sleep(1)

Here we have an infinite loop. If a file is found we call break and exit the loop.

My first answer used a nested combination of while and for and the break only exited the inner loop, so that wasn't going to work.

import os,time

def file_exists(path):
    for dir, sub_dirs, files in os.walk(path):
        return files

path = r'C:\Users\test'
while True:
    if file_exists(path):
        print("file detected")
        break
    else:
        print("no files at this level")
        time.sleep(1)
Related