简体   繁体   中英

How to make python spot a folder and print its files

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.

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.

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