I am trying to find all the .c
files in a directory using Python.
I wrote this, but it is just returning me all files - not just .c
files.
import os import re results = [] for folder in gamefolders: for f in os.listdir(folder): if re.search('.c', f): results += [f] print results
How can I just get the .c
files?
For finding a specific file type, simply use the 'type:' command, followed by the file extension. For example, you can find . docx files by searching 'type: . docx'.
Use the os. listdir('path') function to get the list of all files of a directory. This function returns the names of the files and directories present in the directory.
try changing the inner loop to something like this
results += [each for each in os.listdir(folder) if each.endswith('.c')]
Try "glob":
>>> import glob >>> glob.glob('./[0-9].*') ['./1.gif', './2.txt'] >>> glob.glob('*.gif') ['1.gif', 'card.gif'] >>> glob.glob('?.gif') ['1.gif']
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