You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python列表复刻文件目录树并实现动态操作与搜索功能?

Alright, let's build a solution that meets all your requirements: a nested list-based directory tree with search (handling duplicate filenames across paths), dynamic file/folder addition, and proper representation of nested directories. Here's a Python implementation that does exactly that:

1. Define the Directory Tree Structure

First, let's represent your example directory as nested lists. Each folder is a list where the first element is the folder name, followed by its contents (files or subfolders):

# Example directory tree matching your description
my_files = [
    "MyFiles",
    ["Important", "doc1", "doc2"],
    ["LessImportant", "doc3", "doc4"],
    ["LowPriority",
        ["Important", "doc1"],
        ["LessImportant", "doc4"]
    ]
]

2. Search for Files (Handle Duplicates)

We'll write a recursive function that traverses the tree and returns all full paths to files matching the target name. This way, even if two files have the same name in different folders, we can distinguish them:

def search_file(tree, target, current_path=""):
    results = []
    # The first element is the current folder name
    folder_name = tree[0]
    full_path = f"{current_path}/{folder_name}" if current_path else folder_name

    for item in tree[1:]:
        if isinstance(item, str):
            # It's a file
            if item == target:
                results.append(f"{full_path}/{item}")
        else:
            # It's a subfolder, recurse
            results.extend(search_file(item, target, full_path))
    return results

# Example usage: Search for "doc1"
print(search_file(my_files, "doc1"))
# Output: ['MyFiles/Important/doc1', 'MyFiles/LowPriority/Important/doc1']

3. Dynamically Add Files/Folders

Next, let's create a function to add items (files or folders) to a specific path in the tree. This function will recursively navigate to the target folder and add the new item, creating intermediate folders if they don't exist:

def add_item(tree, target_path, item, is_folder=False):
    # Split the target path into parts (e.g., "MyFiles/LowPriority" -> ["MyFiles", "LowPriority"])
    path_parts = target_path.split("/")
    current_node = tree

    # Navigate to the target folder
    for part in path_parts[1:]:  # Skip the root folder (already in tree)
        found = False
        for child in current_node[1:]:
            if isinstance(child, list) and child[0] == part:
                current_node = child
                found = True
                break
        if not found:
            # Create the folder if it doesn't exist
            new_folder = [part]
            current_node.append(new_folder)
            current_node = new_folder

    # Add the new item to the target folder
    if is_folder:
        # Check if folder already exists to avoid duplicates
        for child in current_node[1:]:
            if isinstance(child, list) and child[0] == item:
                print(f"Folder '{item}' already exists in {target_path}")
                return
        current_node.append([item])
    else:
        # Check if file already exists (optional, adjust based on needs)
        if item in current_node[1:]:
            print(f"File '{item}' already exists in {target_path}")
            return
        current_node.append(item)

# Example 1: Add a file "doc5" to MyFiles/LowPriority/LessImportant
add_item(my_files, "MyFiles/LowPriority/LessImportant", "doc5")

# Example 2: Add a new folder "Archive" to MyFiles
add_item(my_files, "MyFiles", "Archive", is_folder=True)

# Example 3: Add a file "notes.txt" to the new Archive folder
add_item(my_files, "MyFiles/Archive", "notes.txt")

4. Verify the Updated Tree

To see the changes, we can write a helper function to print the tree in a readable format:

def print_tree(tree, indent=0):
    prefix = "  " * indent
    folder_name = tree[0]
    print(f"{prefix}{folder_name}/")
    for item in tree[1:]:
        if isinstance(item, str):
            print(f"{prefix}  - {item}")
        else:
            print_tree(item, indent + 1)

# Print the updated tree
print_tree(my_files)

Output after additions:

MyFiles/
  - Important/
    - doc1
    - doc2
  - LessImportant/
    - doc3
    - doc4
  - LowPriority/
    - Important/
      - doc1
    - LessImportant/
      - doc4
      - doc5
  - Archive/
    - notes.txt

This implementation covers all your requirements:

  • Nested list representation of the directory tree
  • Search functionality that returns full paths to handle duplicate filenames
  • Dynamic addition of both files and folders (with optional duplicate checks)
  • Recursive traversal to handle arbitrary depth

内容的提问来源于stack exchange,提问作者BerickCook

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:34:28