【发布时间】:2020-05-18 06:06:44
【问题描述】:
我有以下函数,它遍历给定目录的根目录并抓取所有子目录并将它们放入列表中。这部分工作,有点。
目标是确定以数字命名的最高(最大数字)文件夹。 假设该文件夹仅包含以数字命名的文件夹,并且不包含文件的字母数字文件夹,我很好。但是,如果存在未用数字命名的文件或文件夹,我会遇到问题,因为脚本似乎正在收集所有子目录和文件,并将所有内容都放入列表中。
我只需要找到那些命名为数字的文件夹,而忽略其他任何内容。
Example folder structure for c:\Test
\20200202\
\20200109\
\20190308\
\Apples\
\Oranges\
New Document.txt
这可以遍历目录,但会将所有内容都放在列表中,而不仅仅是数字子文件夹。
#Example code
import os
from pprint import pprint
files=[]
MAX_DEPTH = 1
folders = ['C:\\Test']
for stuff in folders:
for root, dirs, files in os.walk(stuff, topdown=True):
for subdirname in dirs:
files.append(os.path.join(subdirname))
#files.append(os.path.join(root, subdirname)) will give full directory
#print("there are", len(files), "files in", root) will show counts of files per directory
if root.count(os.sep) - stuff.count(os.sep) == MAX_DEPTH - 1:
del dirs[:]
pprint(max(files))
max(files) 的当前结果: 新建文档.txt
所需的输出: 20200202
到目前为止我所做的尝试:
我尝试在将每个元素添加到列表之前将其捕获,查看 subdirname 的字符串是否可以转换为 int,然后将其添加到列表中。这无法将数字子目录名转换为 int,并且以某种方式(我不知道如何)将 New Document.txt 文件添加到列表中。
files=[]
MAX_DEPTH = 1
folders = ['C:\\Test']
for stuff in folders:
for root, dirs, files in os.walk(stuff, topdown=True):
for subdirname in dirs:
try:
subdirname = int(subdirname)
print("Found subdir named " + subdirname + " type: " + type(subdirname))
files.append(os.path.join(subdirname))
except:
print("Error converting " + str(subdirname) + " to integer")
pass
#files.append(os.path.join(root, subdirname)) will give full directory
#print("there are", len(files), "files in", root) will show counts of files per directory
if root.count(os.sep) - stuff.count(os.sep) == MAX_DEPTH - 1:
del dirs[:]
return (input + "/" + max(files))
我还尝试将所有内容附加到列表中,然后使用下面的内容创建第二个列表(即,没有 try/except),但我最终得到了一个空列表。我不知道为什么,我不知道从哪里/如何开始寻找。在应用以下内容之前在列表中使用 'type' 表明列表中的所有内容都是 str 类型。
list2 = [x for x in files if isinstance(x,int) and not isinstance(x,bool)]
【问题讨论】:
标签: python python-3.x list