簡體   English   中英

Python:列出帶有文件名的目錄/子目錄

[英]Python: List directories/sub-directories with file names

我正在嘗試按時間修改順序列出目錄、子目錄文件。 我用下面的代碼得到了想要的結果。 但是當把這段代碼放在函數中時,我只得到最后一行。

import os
from fnmatch import fnmatch

root = 'Test\\inputs\\'
pattern = "*"

for path, subdirs, files in sorted(os.walk(root), reverse=True):
    for name in files:
        if fnmatch(name, pattern):
            print(os.path.join(path, name))

輸出:

Test\inputs\backup\cdr_dsw
Test\inputs\backup\cdr_ds.xml
Test\inputs\backup\dsdf.xml
Test\inputs\testing.txt

same code using function:

import os
from fnmatch import fnmatch
root = 'Test\\inputs\\'
pattern = "*"

def Listdir():
    X = []
    for path, subdirs, files in sorted(os.walk(root), reverse=True):
        for name in files:
            if fnmatch(name, pattern):
                X.append(os.path.join(path, name))
                return X

print(Listdir())

output:

Test\inputs\backup\cdr_dsw

不知道我在做什么錯誤。 請幫助糾正我的錯誤。 我想將其用作函數。

提前致謝。

因為你把return X寫入if ,它只返回第一個,你可以把它寫在for ,所以你可以在附加所有路徑時返回 X

def Listdir():
    X = []
    for path, subdirs, files in sorted(os.walk(root), reverse=True):
        for name in files:
            if fnmatch(name, pattern):
                X.append(os.path.join(path, name))
     return X

print(Listdir())

暫無
暫無

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

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