[英]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 ","")
The result that comes out of here is the "Directory of" text at the beginning, I am trying to remove this text with the replace method so that only the file names remain, but it works directly and I cannot do the replacement I want.从这里出来的结果是开头的“目录”文本,我试图用替换方法删除这个文本,以便只保留文件名,但它直接工作,我不能做我想要的替换。 How can fix this problem(i am new at python)
如何解决这个问题(我是 python 新手)
os.system()
simply prints its results to the console. os.system()
只是将其结果打印到控制台。 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
).如果您希望将字符串传递回 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)
Notice how the cwd=
keyword avoids having to permanently change the working directory of the current Python process.请注意
cwd=
关键字如何避免必须永久更改当前 Python 进程的工作目录。
I factored out the findstr Directory
too;我也分解了
findstr Directory
; it usually makes sense to run as little code as possible in a subprocess.在子进程中运行尽可能少的代码通常是有意义的。
text=True
requires Python 3.7 or newer; text=True
需要 Python 3.7 或更新版本; in some older versions, it was misleadingly called universal_newlines=True
.在一些旧版本中,它被误导性地称为
universal_newlines=True
。
If your target is simply to find files matching *.docx
in subdirectories, using a subprocess is arcane and inefficient;如果您的目标只是在子目录中查找与
*.docx
匹配的文件,那么使用子进程是晦涩难懂且效率低下的; just do做就是了
import glob
def folderFinder():
return glob.glob(r"C:\**\*.docx", recursive=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.