【问题标题】:Python: Identifying numerically names folders in a folder structurePython:识别文件夹结构中的数字名称文件夹
【发布时间】: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))

ma​​x(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


    【解决方案1】:

    我将继续在这里回答我自己的问题:

    改变方法完全有帮助,并且显着更快、更简单。

    #the find_newest_date function looks for a folder with the largest number and assumes that is the newest data
    def find_newest_date(input):
        intlistfolders = []
        list_subfolders_with_paths = [f.name for f in os.scandir(input) if f.is_dir()]
        for x in list_subfolders_with_paths:
            try:
                intval = int(x)
                intlistfolders.append(intval)
            except:
                pass
        return (input + "/" + str(max(intlistfolders)))
    

    解释:

    • scandir 比 walk 快 3 倍。 directory performance
    • scandir 还允许使用 f.name 仅拉出文件夹 名称,或 f.path 获取路径。

    因此,使用 scandir 加载包含所有子目录的列表。

    1. 遍历列表,并尝试将每个值转换为整数。 我不知道为什么它在前面的示例中不起作用,但它 在这种情况下有效。
    2. try 语句的第一部分转换为整数。
    3. 如果转换失败,则运行 except 子句,并且“通过” 本质上是一个空语句。它什么都不做。
    4. 然后,最后,用字符串加入输入目录 最大数值的表示(即最近日期 在这种情况下是文件夹)。

    函数被调用:

    folder_named_path = find_newest_date("C:\\Test") or something similar. 
    

    【讨论】:

      【解决方案2】:

      尝试使用正则表达式匹配 dirs。num = r”[0-9]+” 是您的正则表达式。像re.findall(num,subdirname) 这样的东西会返回一个匹配的字符串,它是一个或多个数字。

      【讨论】:

      • 谢谢 - 我不擅长正则表达式,所以我在使用替代方法提供的答案中更进一步。
      猜你喜欢
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 2012-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多