Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

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 ","")

The result that comes out of here is the "Directory of" text at the beginning, I am trying to remove this text with the replace method so that only the file names remain, but it works directly and I cannot do the replacement I want. How can fix this problem(i am new at python)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

os.system() simply prints its results to the console. If you want the strings to be passed back to Python, you need to use subprocess (or one of the wrappers which ends up calling subprocess anyway eventually, like 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)

Notice how the cwd= keyword avoids having to permanently change the working directory of the current Python process.

I factored out the findstr Directory too; it usually makes sense to run as little code as possible in a subprocess.

text=True requires Python 3.7 or newer; in some older versions, it was misleadingly called universal_newlines=True.

If your target is simply to find files matching *.docx in subdirectories, using a subprocess is arcane and inefficient; just do

import glob

def folderFinder():
    return glob.glob(r"C:***.docx", recursive=True)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...