简体   繁体   English

如何使python发现文件夹并打印其文件

[英]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. 我希望能够使python打印C驱动器中的所有内容。 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. 免责声明 os.walk很好,我在这里提供一个更简单的解决方案。

If you're using python 3.5 or above, you can use glob.glob with '**' and recursive=True 如果您使用的是python 3.5或更高版本,则可以将glob.glob'**'recursive=True

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

Please note that getting the entire file list of C:\\ drive can take a lot of time. 请注意,获取C:\\驱动器的整个文件列表可能需要很多时间。

If you don't need the entire list at the same time, glob.iglob is a reasonable choice. 如果您不需要同时使用整个列表,则glob.iglob是一个合理的选择。 The usage is the same, except that you get an iterator instead of a list. 除了使用迭代器而不是列表以外,用法是相同的。

To print everything under C:\\ 在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. 但是,如果您没有可用的python 3.5,则可以查看glob.py的源代码并将其调整为适合您的用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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