簡體   English   中英

如何用替換方法替換 os.system output?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM