Reputation: 41
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.
Upvotes: 4
Views: 3822
Reputation: 15537
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}")
Upvotes: 4
Reputation: 1243
I would do the following:
Loop through each file in the directory, get the names as strings and check to see if they begin with myfile
by splitting the string on the .
you can compare what you are looking for with what you have.
Upvotes: 0
Reputation: 1608
Also you can have a look to os.walk function if you want to look inside subdirectories.
http://docs.python.org/library/os.html#os.walk
Upvotes: 0
Reputation: 72855
The format
(by which I mean you assume file type) is not related to its extension (which is part of its name).
If you're on a UNIX, you can use the find command. find myfolder -name myfile
should work.
If you want a complete listing, you can either use find without any arguments, use ls
with the -R
option or use the tree
command. All of these are on UNIX.
Upvotes: 0
Reputation: 11046
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) ):
Upvotes: 5