Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How can I find all files with a particular extension?

Tags:

python

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?

like image 368
BeeBand Avatar asked Aug 31 '10 11:08

BeeBand


People also ask

How do I search for a specific file extension?

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'.

How do I get a list of files in a directory in Python?

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.


2 Answers

try changing the inner loop to something like this

results += [each for each in os.listdir(folder) if each.endswith('.c')] 
like image 141
deif Avatar answered Sep 29 '22 10:09

deif


Try "glob":

>>> import glob >>> glob.glob('./[0-9].*') ['./1.gif', './2.txt'] >>> glob.glob('*.gif') ['1.gif', 'card.gif'] >>> glob.glob('?.gif') ['1.gif'] 
like image 24
Maciej Kucharz Avatar answered Sep 29 '22 10:09

Maciej Kucharz