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
Bhargav rao
source share