![](/img/trans.png)
[英]How to zip a folder and all of its files in Python, while preserving the folder name and relative paths for its contents?
[英]How to make python spot a folder and print its files
我希望能夠使python打印C驅動器中的所有內容。 我已經弄清楚了,可以在驅動器的第一“層”上打印內容,
def filespotter():
import os
path = 'C:/'
dirs = os.listdir( path )
for file in dirs:
print(file)
但我希望它進入其他文件夾並打印其他所有文件夾中的內容。
免責聲明 os.walk
很好,我在這里提供一個更簡單的解決方案。
如果您使用的是python 3.5或更高版本,則可以將glob.glob
與'**'
和recursive=True
例如: glob.glob(r'C:\\**', recursive=True)
請注意,獲取C:\\驅動器的整個文件列表可能需要很多時間。
如果您不需要同時使用整個列表,則glob.iglob
是一個合理的選擇。 除了使用迭代器而不是列表以外,用法是相同的。
在C:\\下打印所有內容
for filename in glob.iglob(r'C:\**', recursive=True):
print(filename)
它會盡快給您輸出。
但是,如果您沒有可用的python 3.5,則可以查看glob.py的源代碼並將其調整為適合您的用例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.