![](/img/trans.png)
[英]How do I replace os.system(“mkdir ” _testName) with subprocess.call in Python?
[英]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 ","")
從這里出來的結果是開頭的“目錄”文本,我試圖用替換方法刪除這個文本,以便只保留文件名,但它直接工作,我不能做我想要的替換。 如何解決這個問題(我是 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.