我想构建一个程序,它使用一些基本代码来读取文件夹并告诉我文件夹中有多少文件。这是我目前的做法:
import os
folders = ['Y:\\path1', 'Y:\\path2', 'Y:\\path3']
for stuff in folders:
for root, dirs, files in os.walk(stuff, topdown=True):
print("there are", len(files), "files in", root)
在“主”文件夹中有多个文件夹之前,这非常有效,因为由于文件夹/文件管理不善,它可能会返回一长串垃圾文件。所以我最多只想到第二级。例子:
Main Folder
---file_i_want
---file_i_want
---Sub_Folder
------file_i_want <--*
------file_i want <--*
------Sub_Folder_2
---------file_i_dont_want
---------file_i_dont_want
我知道如何只用 abreak
和del dirs[:]
从这篇文章和这篇文章中获取到第一级。
import os
import pandas as pd
folders = ['Y:\\path1', 'Y:\\path2', 'Y:\\path3']
for stuff in folders:
for root, dirs, files in os.walk(stuff, topdown=True):
print("there are", len(files), "files in", root)
del dirs[:] # or a break here. does the same thing.
但是无论我如何搜索,我都无法找到如何深入两层。我可能只是不理解上面的其他帖子还是什么?我在想类似的东西,del dirs[:2]
但无济于事。有人可以指导我或向我解释如何做到这一点吗?