如何用replace方法替换os.system输出?

2024-09-24 22:23:37 发布

您现在位置:Python中文网/ 问答频道 /正文

def folderFinder():
   import os
   os.chdir("C:\\")
   command = "dir *.docx /s | findstr Directory"
   os.system(command).replace("Directory of ","")

从这里出来的结果是开始时的“Directory of”文本,我试图用replace方法删除此文本,以便只保留文件名,但它可以直接工作,我无法执行我想要的替换。如何解决这个问题(我是python新手)


Tags: of文本importosdefdirsystemdirectory
1条回答
网友
1楼 · 发布于 2024-09-24 22:23:37

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)

相关问题 更多 >