如何用替换方法替换 os.system 输出?
How can I replace os.system output with replace method?
def folderFinder():
import os
os.chdir("C:\")
command = "dir *.docx /s | findstr Directory"
os.system(command).replace("Directory of ","")
这里出来的结果是开头的“Directory of”文本,我试图用replace方法删除这段文本,只保留文件名,但它直接工作,我做不到我想要的替代品。如何解决这个问题(我是 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)
def folderFinder():
import os
os.chdir("C:\")
command = "dir *.docx /s | findstr Directory"
os.system(command).replace("Directory of ","")
这里出来的结果是开头的“Directory of”文本,我试图用replace方法删除这段文本,只保留文件名,但它直接工作,我做不到我想要的替代品。如何解决这个问题(我是 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)