我试图使一个脚本列出所有目录,子目录,和文件在一个给定的目录。 我试了一下:

import sys, os

root = "/home/patate/directory/"
path = os.path.join(root, "targetdirectory")

for r, d, f in os.walk(path):
    for file in f:
        print(os.path.join(root, file))

不幸的是,它不能正常工作。 我得到了所有文件,但没有它们的完整路径。

例如,如果dir结构体为:

/home/patate/directory/targetdirectory/123/456/789/file.txt

它将打印:

/home/patate/directory/targetdirectory/file.txt

我需要的是第一个结果。任何帮助都将不胜感激!谢谢。


当前回答

你可以看看我做的这个样品。它使用os.path.walk函数,该函数已被弃用。使用列表存储所有文件路径

root = "Your root directory"
ex = ".txt"
where_to = "Wherever you wanna write your file to"
def fileWalker(ext,dirname,names):
    '''
    checks files in names'''
    pat = "*" + ext[0]
    for f in names:
        if fnmatch.fnmatch(f,pat):
            ext[1].append(os.path.join(dirname,f))


def writeTo(fList):

    with open(where_to,"w") as f:
        for di_r in fList:
            f.write(di_r + "\n")






if __name__ == '__main__':
    li = []
    os.path.walk(root,fileWalker,[ex,li])

    writeTo(li)

其他回答

无法评论,所以在这里写下答案。这是我见过的最清晰的一句话:

import os
[os.path.join(path, name) for path, subdirs, files in os.walk(root) for name in files]

这只是一个附加功能,有了它,你可以将数据转换成CSV格式

import sys,os
try:
    import pandas as pd
except:
    os.system("pip3 install pandas")
    
root = "/home/kiran/Downloads/MainFolder" # it may have many subfolders and files inside
lst = []
from fnmatch import fnmatch
pattern = "*.csv"      #I want to get only csv files 
pattern = "*.*"        # Note: Use this pattern to get all types of files and folders 
for path, subdirs, files in os.walk(root):
    for name in files:
        if fnmatch(name, pattern):
            lst.append((os.path.join(path, name)))
df = pd.DataFrame({"filePaths":lst})
df.to_csv("filepaths.csv")

以防万一……获取目录中的所有文件和匹配某些模式的子目录(例如*.py):

import os
from fnmatch import fnmatch

root = '/some/directory'
pattern = "*.py"

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

如果你想在SharePoint上列出文件这就是你列出它的方式。你的路径可能会从“\teams\”部分开始

    import os
    root = r"\\mycompany.sharepoint.com@SSL\DavWWWRoot\teams\MyFolder\Policies and Procedures\Deal Docs\My Deals"
    list = [os.path.join(path, name) for path, subdirs, files in os.walk(root) for name in files]
    print(list)

简单一点的一行代码:

import os
from itertools import product, chain

chain.from_iterable([[os.sep.join(w) for w in product([i[0]], i[2])] for i in os.walk(dir)])