List accounting with if conditional to get a list of files of a certain type

Roughly following the logic of combining lists with if-else described in this solution , I try to get a list of files with specific extensions in the parent directory.

Here is a long form of code:

mxd_list = [] for top_dir, dir_list, obj_list in os.walk(top_path): for obj in obj_list: if obj.endswith('.mxd'): mxd_list.append(os.path.join(top_dir, obj)) 

This is my current attempt to consolidate this using list comprehension. Although it is running, the list is empty.

 for top_dir, dir_list, obj_list in os.walk(top_path): mxd_list = [os.path.join(top_dir, obj) for obj in obj_list if obj.endswith('.mxd')] 
+2
python list list-comprehension glob
source share
2 answers
You were very close. You need to add to the list, which is outside the loop
 mxd_list = [] for top_dir, dir_list, obj_list in os.walk(top_path): mxd_list.extend([os.path.join(top_dir, obj) for obj in obj_list if obj.endswith('.mxd')]) 

The error is that: at each iteration of the for loop for the list, comp will generate a list specific to that iteration only, so you need to extend each of the list generated after each iteration of the external variable, mxd_list .

Note. [ are redundant in the sense that removing them will make the contents an expression of a generator. This statement can be written as mxd_list.extend(os.path.join(top_dir, obj) for obj in obj_list if obj.endswith('.mxd')) .

Another way to do this is Using glob.iglob

As Padraic mentions

 mxd_list = [] for top_dir, dir_list, obj_list in os.walk(top_path): mxd_list.extend(iglob(top_dir+"/*.mxd")) 

This is the best way to do this. But do not forget the import module, i.e. from glob import iglob

+4
source share

The list of matching file names can be computed using a single list.

 [os.path.join(d,f) for d,_,fl in os.walk(top) for f in fl if f.endswith(ext)] 
0
source share

All Articles