问题描述
def folderFinder():
import os
os.chdir("C:\\")
command = "dir *.docx /s | findstr Directory"
os.system(command).replace("Directory of ","")
从这里出来的结果是开头的“目录”文本,我试图用替换方法删除此文本,以便只保留文件名,但它直接工作,我无法进行替换我想要。如何解决这个问题(我是 Python 新手)
解决方法
os.system()
只是将其结果打印到控制台。如果您希望将字符串传递回 Python,则需要使用 subprocess
(或最终最终调用 subprocess
的包装器之一,例如 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)
请注意 cwd=
关键字如何避免永久更改当前 Python 进程的工作目录。
我也分解了 findstr Directory
;在子进程中运行尽可能少的代码通常是有意义的。
text=True
需要 Python 3.7 或更新版本;在一些旧版本中,它被误导地称为 universal_newlines=True
。
如果您的目标只是在子目录中查找与 *.docx
匹配的文件,则使用子进程既神秘又低效;就做
import glob
def folderFinder():
return glob.glob(r"C:\**\*.docx",recursive=True)