簡體   English   中英

Python:識別文件夾結構中的數字名稱文件夾

[英]Python: Identifying numerically names folders in a folder structure

我有以下函數,它遍歷給定目錄的根目錄並抓取所有子目錄並將它們放入列表中。 這部分工作,有點。

目標是確定最高(最大數字)數字命名的文件夾。 假設文件夾只包含數字命名的文件夾,而不包含文件的字母數字文件夾,我很好。 但是,如果存在未以數字命名的文件或文件夾,我會遇到問題,因為腳本似乎正在收集所有子目錄和文件,並將所有內容都放入列表中。

我只需要找到那些命名為數字的文件夾,而忽略其他任何內容。

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) 的當前結果: New Document.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)]

我將繼續在這里回答我自己的問題:

改變方法完全有幫助,並使其更快、更簡單。

#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 倍。 目錄性能
  • scandir 還允許使用 f.name 僅提取文件夾名稱,或使用 f.path 獲取路徑。

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

  1. 遍歷列表,並嘗試將每個值轉換為整數。 我不知道為什么它在前面的例子中不起作用,但它在這種情況下起作用。
  2. try 語句的第一部分轉換為整數。
  3. 如果轉換失敗,則運行 except 子句,並且 'pass' 本質上是一個空語句。 它什么都不做。
  4. 然后,最后,將輸入目錄與最大數值的字符串表示(即在這種情況下最近日期的文件夾)連接起來。

該函數被調用:

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

嘗試使用正則表達式匹配目錄。 num = r”[0-9]+”是你的正則表達式。 re.findall(num,subdirname)類的東西會返回一個匹配的字符串,它是一個或多個數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM