简体   繁体   中英

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM