I want to list all folders containing docx
files using os()
.walk method in Python 2.7. I managed to do that with code written below, but I want to know if it is possible to limit this list to show only folders containing exactly two specific file types (for example "docx" and "pdf")?
import os
import walk
a = open("output.txt", "w")
for path, subdirs, files in os.walk(r'C:\Users\Stephen\Desktop'):
for filename in files:
if filename.endswith(('.docx')):
f = os.path.join(path, filename)
a.write(str(f) + os.linesep)
Just skip directories where you don't have at least those two extensions; per-directory file lists are limited so it's cheap to use
any()
to test for specific extensions:When the list of extensions to test for gets a bit longer, you may want to just create a set of all available extensions:
>=
tests if the right-hand set is a subset of the left (soextensions
is a superset of the right-hand set); soextensions
should at least contain all for extensions named on the right: