繁体   English   中英

如何获取子目录名称列表、每个目录中的文件名以及每个目录的路径(Python)

[英]how to get a list of sub directory names, the file names in each and the paths to each of these (Python)

我想在 python 中创建一个子目录列表。该列表将由列表组成。 每个子列表中的第一项是子目录名称及其作为元组的路径。 然后是该子目录中的文件及其路径。

示例:文件结构

assets/
      location1/
                file1.png
                file2.png
                file3.png
      location2/
                file4.png
                file5.png

会返回:

[
  [
    ('location1', 'assets/location1'), 
    ('file1.png', 'assets/location1/file1.png'), 
    ('file2.png', 'assets/location1/file2.png'), 
    ('file3.png', 'assets/location1/file3.png')
  ],
  [
    ('location2', 'assets/location2'), 
    ('file4.png', 'assets/location2/file4.png'), 
    ('file5.png', 'assets/location2/file5.png')
  ]
]

希望这是有道理的,提前感谢您的宝贵时间!

这是我过去用过的一个例子:


import os
import re

def crawler(path: str, ignore_hidden: bool = True) -> list[dict]:
    """
    It crawls a directory and returns a list of dictionaries, each dictionary representing a file or
    directory

    Args:
      path (str): The path to the directory you want to crawl.
      ignore_hidden (bool): If True, ignore hidden files and directories. Defaults to True

    Returns:
      A list of dictionaries.
    """

    files = []
    for obj in os.listdir(path):
        obj_path = os.path.normpath(os.path.join(path, obj))
        file = {
            "name": obj,
            "path": os.path.relpath(obj_path),
        }
        pattern = r"^\.\w+$"
        match = re.search(pattern, obj, re.IGNORECASE)
        if match and ignore_hidden:
            continue
        if os.path.isfile(obj_path):
            file["type"] = "file"
        else:
            file["type"] = "dir"
            file["files"] = crawler(obj_path)
        files.append(file)
    return files

例如 output:

In [1]: crawler(os.getcwd())
Out[1]:
[{'name': 'about.txt', 'path': 'about.txt', 'type': 'file'},
 {'name': 'android-chrome-192x192.png',
  'path': 'android-chrome-192x192.png',
  'type': 'file'},
 {'name': 'android-chrome-512x512.png',
  'path': 'android-chrome-512x512.png',
  'type': 'file'},
 {'name': 'apple-touch-icon.png',
  'path': 'apple-touch-icon.png',
  'type': 'file'},
 {'name': 'favicon-16x16.png', 'path': 'favicon-16x16.png', 'type': 'file'},
 {'name': 'favicon-32x32.png', 'path': 'favicon-32x32.png', 'type': 'file'},
 {'name': 'favicon.ico', 'path': 'favicon.ico', 'type': 'file'},
 {'name': 'New folder',
  'path': 'New folder',
  'type': 'dir',
  'files': [{'name': 'New Text Document.txt',
    'path': 'New folder\\New Text Document.txt',
    'type': 'file'}]},
 {'name': 'site.webmanifest', 'path': 'site.webmanifest', 'type': 'file'}]

你可以使用 python os function 你可以使用 os 路径和 os listdir 和 os 路径 isdir

# is function return all the subdirectories as you ask at the question 
def get_subdirectories(directory):
    subdir = []

    for item in os.listdir(directory):
        path = os.path.join(directory, item)

        if os.path.isdir(path):
            subdir.append([(item, path)])
            subdir += get_subdirectories(path)
        else:
            subdir[-1].append((item, path))

    return subdir 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM