Let's say I want to search for a file name "myfile" in a folder named "myfolder", how can I do it without knowing the format of the file? Another question: how to list all files of a folder and all the files of it's subfolders (and so on)? Thank you.
import os
import glob
path = 'myfolder/'
for infile in glob.glob( os.path.join(path, 'myfile.*') ):
print "current file is: " + infile
if you want to list all the files in the folder, simply change the for loop into
for infile in glob.glob( os.path.join(path) ):
To list all files in a folder and its subfolders and so on, use the os.walk function:
import os
for root, dirs, files in os.walk('/blah/myfolder'):
for name in files:
if 'myfile' in name:
print (f"Found {name}")
In the easier case where you just want to look in 'myfolder' and not its subfolders, just use the os.listdir function:
import os
for name in os.listdir('/blah/myfolder'):
if 'myfile' in name:
print (f"Found {name}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With