I have lots of files in a directory, lets say around 100, most of their file names begin with "Mod", i need to add all filenames that begin with "Mod" to a list so i can reference them later in my code. Any help? Thanks!
Asked
Active
Viewed 1,960 times
2 Answers
2
Use the glob package.
import glob
filepaths = glob.glob('/path/to/file/Mod*')
More generally, you can use os.listdir
. Unlike glob
, it only returns the last part of the filename (without the full path).
import os
directory = '/path/to/directory'
filenames = os.listdir(directory )
full_filepaths = [os.path.join(directory, f) for f in filenames]
only_files = [f for f in full_filepaths if os.path.isfile(f)]

Brendan Abel
- 35,343
- 14
- 88
- 118
0
You can use glob library to find the files with the given pattern:
import glob,os
mylist=[]
os.chdir("/mydir")
for file in glob.glob("Mod*"):
mylist.append(file)
print mylist
or you can use os.walk
for root, dirs, files in os.walk('/mydir'):
for names in files:
if names.startswith("Mod"):
mylist.append(os.path.join(root, names))

Dalek
- 4,168
- 11
- 48
- 100