我想构建一个程序,使用一些基本代码来读取文件夹并告诉我文件夹中有多少文件。
这是我目前的做法:
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
我知道如何使用 break
和 del dirs[:]
从 this post 进入第一层和 also this post .
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]
但无济于事。有人可以指导我或向我解释如何完成此操作吗?
你可以这样做:
depth = 2
# [1] abspath() already acts as normpath() to remove trailing os.sep
#, and we need ensures trailing os.sep not exists to make slicing accurate.
# [2] abspath() also make /../ and ////, "." get resolved even though os.walk can returns it literally.
# [3] expanduser() expands ~
# [4] expandvars() expands $HOME
# WARN: Don't use [3] expanduser and [4] expandvars if stuff contains arbitrary string out of your control.
#stuff = os.path.expanduser(os.path.expandvars(stuff)) # if trusted source
stuff = os.path.abspath(stuff)
for root,dirs,files in os.walk(stuff):
if root[len(stuff):].count(os.sep) < depth:
for f in files:
print(os.path.join(root,f))
关键是:if root[len(stuff):].count(os.sep) < depth
它删除了 stuff
来自 root
, 所以结果是相对于 stuff
.只需计算文件分隔符的数量即可。
深度就像find
在 Linux 中找到的命令,即 -maxdepth 0
表示什么都不做,-maxdepth 1
仅扫描第一级文件,-maxdepth 2
扫描文件包含子目录。
当然,它仍然会扫描完整的文件结构,但除非它非常深,否则它会起作用。
另一个解决方案是只使用 os.listdir
递归地(通过目录检查)最大递归级别,但如果你不需要它,那就有点棘手了。由于这并不难,这里是一种实现方式:
def scanrec(root):
rval = []
def do_scan(start_dir,output,depth=0):
for f in os.listdir(start_dir):
ff = os.path.join(start_dir,f)
if os.path.isdir(ff):
if depth<2:
do_scan(ff,output,depth+1)
else:
output.append(ff)
do_scan(root,rval,0)
return rval
print(scanrec(stuff)) # prints the list of files not below 2 deep
备注:os.listdir
和 os.path.isfile
执行 2 stat
调用不是最优的。在 Python 3.5 中,使用 os.scandir
可以避免重复调用。