0

I want to be able to make python print everything in my C drive. I have figured out this to print whats on the first "layer" of the drive,

def filespotter():
import os
path = 'C:/'
dirs = os.listdir( path )
for file in dirs:
    print(file)

but I want it to go into the other folders and print what is in every other folder.

MonkeyMaker21
  • 15
  • 1
  • 4
  • 1
    Possible duplicate of [How to list all files of a directory in Python](http://stackoverflow.com/questions/3207219/how-to-list-all-files-of-a-directory-in-python) – Sencer H. Feb 26 '16 at 14:19
  • @SencerH. The quesion you shared asks how to list the contents of a directory only, not its subdirectories as well. – Anmol Singh Jaggi Feb 26 '16 at 15:44
  • 1
    Possible duplicate of http://stackoverflow.com/questions/16953842/using-os-walk-to-recursively-traverse-directories-in-python – Anmol Singh Jaggi Feb 26 '16 at 15:45

1 Answers1

0

Disclaimer os.walk is just fine, I'm here to provide a easier solution.

If you're using python 3.5 or above, you can use glob.glob with '**' and recursive=True

For example: glob.glob(r'C:\**', recursive=True)

Please note that getting the entire file list of C:\ drive can take a lot of time.

If you don't need the entire list at the same time, glob.iglob is a reasonable choice. The usage is the same, except that you get an iterator instead of a list.

To print everything under C:\

for filename in glob.iglob(r'C:\**', recursive=True):
    print(filename)

It gives you output as soon as possible.

However if you don't have python 3.5 available, you can see the source of glob.py and adapt it for your use case.

130333
  • 86
  • 7