i want to make a program to search all my pc and make list of result , so first of all i can not search all partition together and have to use os.chdir("")
on the other hand when some Suffix dose not exit in it make a error and stop program.
My code:
os.chdir("E:\") txt = subprocess.check_output("dir /S /B *.txt" , shell=True).decode().split() dll = subprocess.check_output("dir /S /B *.dll" , shell=True).decode().split() png = subprocess.check_output("dir /S /B *.png" , shell=True).decode().split() gif = subprocess.check_output("dir /S /B *.gif" , shell=True).decode().split() tlb = subprocess.check_output("dir /S /B *.tlb" , shell=True).decode().split() ALL = txt + dll + png + gif + tlb
And result:
File Not Found Traceback (most recent call last): File "e:codelockdebug.py", line 12, in <module> png = subprocess.check_output("dir /S /B *.png" , shell=True).decode().split() File "C:Users81332668AppDataLocalProgramsPythonPython39libsubprocess.py", line 420, in check_output return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, File "C:Users81332668AppDataLocalProgramsPythonPython39libsubprocess.py", line 524, in run raise CalledProcessError(retcode, process.args, subprocess.CalledProcessError: Command 'dir /S /B *.png' returned non-zero exit status 1.
What sould i do to debug and improve my code!!
Advertisement
Answer
Your problem is you’re using check_output()
which will raise an exception if the command returns a non-zero error code, and dir does that if it finds no files that match.
You should use getoutput
if you don’t care about that.
However, there’s really no need to shell out to dir
5 times here – just use os.walk()
:
import os EXTENSIONS = {".txt", ".dll", ".png", ".gif", ".tlb"} found_files = [] for dirname, dirpaths, filenames in os.walk("E:\"): for filename in filenames: ext = os.path.splitext(filename)[-1] if ext in EXTENSIONS: found_files.append(os.path.join(dirname, filename)) for file in found_files: print(file)