簡體   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