创建单独的文本文件以列出每个目录和子目录中的内容

Der*_*mes 4 command-line directory find

我有一个根文件夹,里面有很多目录和文件。我需要用 name 保存每个子目录中的内容列表list.txt

假设我有

A
|
-----B
|    |---Z
|    |---a.txt
|    |---b.jpg
|
|
|----C
|    |--a.txt
|    |--b.txt
Run Code Online (Sandbox Code Playgroud)

运行命令它应该list.txt在每个子目录中给出一个用逗号分隔的内容。

我已经 # 评论了内容应该是什么...

A
|
-----B
|    |---Z
|    |---a.txt
|    |---b.jpg
|    |---list.txt  # Z,a.txt,b.jpg
|
|
|----C
|    |--a.txt
|    |--b.txt
|    |--list.txt  # a.txt,b.txt
Run Code Online (Sandbox Code Playgroud)

我能列出文件的最接近的是

find . -maxdepth n -type f -printf '%f\n'
Run Code Online (Sandbox Code Playgroud)

但我不知道如何单独保存内容。

请提出一些建议。

Jac*_*ijm 5

下面的脚本将递归地向目录中的所有子目录添加一个列表:

#!/usr/bin/env python3
import os
import sys

for root, dirs, files in os.walk(sys.argv[1]):
    for dr in dirs:
        dr = os.path.join(root, dr)
        open(os.path.join(dr, "list.txt"), "wt").write(
            ",".join(f for f in os.listdir(dr) if f != "list.txt")
            )
Run Code Online (Sandbox Code Playgroud)

使用

  1. 将脚本复制到一个空文件中,另存为 dirlists.py
  2. 以主目录为参数运行它:

    python3 /path/to/dirlists.py /path/to/maindirectory
    
    Run Code Online (Sandbox Code Playgroud)

笔记

如前所述,该脚本将一个 list.txt 添加到所有subdirs。如果您还需要或希望在目录的(根)目录中有一个列表,请提及。

解释

  1. 递归列出(遍历)目录中的所有目录:

    python3 /path/to/dirlists.py /path/to/maindirectory
    
    Run Code Online (Sandbox Code Playgroud)
  2. 为每个人创建一个内容列表:

    os.listdir(dr)
    
    Run Code Online (Sandbox Code Playgroud)
  3. 打开(必要时创建)文本文件并写入列出的内容,不包括可能的早期文件list.txt

    for root, dirs, files in os.walk(sys.argv[1]):
        for dr in dirs:
            dr = os.path.join(root, dr)
    
    Run Code Online (Sandbox Code Playgroud)

编辑

根据评论中的要求:

如果您需要list.txt以逗号结尾的行,只需替换:

os.listdir(dr)
Run Code Online (Sandbox Code Playgroud)

经过:

open(os.path.join(dr, "list.txt"), "wt").write(
    ",".join(f for f in os.listdir(dr) if f != "list.txt")
    )
Run Code Online (Sandbox Code Playgroud)

注意缩进,将替换放置在完全相同的位置