-1

Is there an easy way to check that a file exists in the entire folder structure without having to cycle? (the use of os.walk is necessary)

"if file exist in in my_dir and its sub directories"
    for root, dirs, files in os.walk(my_dir):
       # do stuff
else:
    print("file does not exist")
anas
  • 9
  • 4
  • Does this answer your question? [Python function that similar to bash find command](https://stackoverflow.com/questions/8247157/python-function-that-similar-to-bash-find-command) – azro Jul 18 '20 at 12:30
  • use `break` and unindent your `else` block. – Olvin Roght Jul 18 '20 at 12:33
  • the intent is to first check globally if the file exists, if it exists then start cycling through the folders in search of it, otherwise do other stuff – anas Jul 18 '20 at 12:38
  • So, the file can exist in a directory or any of its subdirectories? In that case you can't avoid having to recursively search through your directories to find the file. – Paul M. Jul 18 '20 at 12:55
  • so I can't check if the file is in that directory or any of its subdirectories without using a cycle? – anas Jul 18 '20 at 13:01

1 Answers1

0

Use glob.glob as follows:

import glob

fname = 'some_file.txt'
my_dir = '/some_dir' # can also be a relative path
files = glob.glob(f'{my_dir}/**/{fname}', recursive=True)
if files: # list of files that match
    # do something

glob.glob will now look for file some_file.txt in directory my_dir or any of its subdirectories.

Booboo
  • 38,656
  • 3
  • 37
  • 60
  • it works fine, I can incorporate this code into a method and avoid having nested loops, thanks a lot! – anas Jul 18 '20 at 13:12