os.system()
simply prints its results to the console. If you want the strings to be passed back to Python, you need to use subprocess
(or one of the wrappers which ends up calling subprocess
anyway eventually, like os.popen
).
import subprocess
def folderFinder():
output = subprocess.check_output("dir *.docx /s", shell=True, text=True, cwd="C:\\")
for line in output.splitlines():
if "Directory" in line and "Directory of " not in line:
print(line)
Notice how the cwd=
keyword avoids having to permanently change the working directory of the current Python process.
I factored out the findstr Directory
too; it usually makes sense to run as little code as possible in a subprocess.
text=True
requires Python 3.7 or newer; in some older versions, it was misleadingly called universal_newlines=True
.
If your target is simply to find files matching *.docx
in subdirectories, using a subprocess is arcane and inefficient; just do
import glob
def folderFinder():
return glob.glob(r"C:\**\*.docx", recursive=True)