繁体   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