0
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)

1
  • What is the output you get and what is the desired output? Commented Jan 11, 2021 at 9:08

1 Answer 1

0

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I ran the code containing glob, it didn't give an error but it give not output
i changed the return with print and got the result as i wanted thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.