2024-09-24 22:23:37 发布
网友
def folderFinder(): import os os.chdir("C:\\") command = "dir *.docx /s | findstr Directory" os.system(command).replace("Directory of ","")
从这里出来的结果是开始时的“Directory of”文本,我试图用replace方法删除此文本,以便只保留文件名,但它可以直接工作,我无法执行我想要的替换。如何解决这个问题(我是python新手)
os.system()只需将结果打印到控制台。如果希望将字符串传递回Python,则需要使用subprocess(或者最终调用subprocess的包装器之一,如os.popen)
os.system()
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进程的工作目录
cwd=
我也算出了findstr Directory;在子流程中运行尽可能少的代码通常是有意义的
findstr Directory
text=True需要Python 3.7或更新版本;在一些旧版本中,它被错误地称为universal_newlines=True
text=True
universal_newlines=True
如果您的目标只是在子目录中查找与*.docx匹配的文件,那么使用子进程是一种晦涩而低效的方法;照办
*.docx
import glob def folderFinder(): return glob.glob(r"C:\**\*.docx", recursive=True)
os.system()
只需将结果打印到控制台。如果希望将字符串传递回Python,则需要使用subprocess
(或者最终调用subprocess
的包装器之一,如os.popen
)请注意
cwd=
关键字如何避免永久更改当前Python进程的工作目录我也算出了
findstr Directory
;在子流程中运行尽可能少的代码通常是有意义的text=True
需要Python 3.7或更新版本;在一些旧版本中,它被错误地称为universal_newlines=True
如果您的目标只是在子目录中查找与
*.docx
匹配的文件,那么使用子进程是一种晦涩而低效的方法;照办相关问题 更多 >
编程相关推荐