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

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

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


当前回答

这只是一个附加功能,有了它,你可以将数据转换成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")

其他回答

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

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")

另一种选择是使用标准库中的glob模块:

import glob

path = "/home/patate/directory/targetdirectory/**"

for path in glob.glob(path, recursive=True):
    print(path)

如果你需要一个迭代器,你可以使用iglob作为替代:

for file in glob.iglob(my_path, recursive=True):
    # ...

使用os.path.join连接目录和文件名:

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

注意在连接中使用path而不是root,因为使用root是不正确的。


在Python 3.4中,添加了pathlib模块以简化路径操作。所以os.path.join的等价代码是:

pathlib.PurePath(path, name)

pathlib的优点是您可以在路径上使用各种有用的方法。如果你使用具体的Path变量,你也可以通过它们进行实际的OS调用,比如改变到一个目录,删除路径,打开它指向的文件等等。

如果你想在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)