简体   繁体   English

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

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

I would like to create a list of sub directories in python. That list would be made of lists.我想在 python 中创建一个子目录列表。该列表将由列表组成。 The first item in each sub-list would be the sub directory name and it's path as a tuple.每个子列表中的第一项是子目录名称及其作为元组的路径。 Then the files in that sub directory and their paths.然后是该子目录中的文件及其路径。

example: File Structure示例:文件结构

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

would return:会返回:

[
  [
    ('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')
  ]
]

Hope that makes sense, thanks in advance for your time!希望这是有道理的,提前感谢您的宝贵时间!

here is an example I have used in the past:这是我过去用过的一个例子:


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

example output:例如 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'}]

you can use the python os function you can use os path and os listdir and os path isdir你可以使用 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.

相关问题 如何在Python中获取目录中的文件名列表 - How to get a list of file names in a directory in Python 如何使用目录的每个子目录中的文件数创建python列表 - How to create a python list with the number of file in each sub directory of a directory 如何使用列名列表来获取 python 中每一列的索引 - how to use a list of column names to get the indices of each column in python Python - 添加文件名(非完整路径)以从目录和子文件夹中列出 - Python - adding file names (not full paths) to list from directory and subfolders 如何编写特定目录中的文件名+每行索引? - How to write file names which are in a certain directory + index of each line? 如何在脚本python3中递归重命名子目录和文件名? - How to rename sub directory and file names recursively in script python3? 如何在python中获取文件名列表并将每个文件名分配为数字以供以后使用? - How can I take a list of file names in python and assign each file name as a number for later use? 在python中将目录的每个文件的路径获取到Array中 - Getting paths of each file of a directory into an Array in python python pandas - 如何为每一行创建一个带有条件的列名列表? - python pandas - how to create for each row a list of column names with a condition? 如何遍历文件路径名列表并删除每个路径名? - How to iterate through a list of file path names and delete each one?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM