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)
但我不知道如何单独保存内容。
请提出一些建议。
下面的脚本将递归地向目录中的所有子目录添加一个列表:
#!/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)
dirlists.py
以主目录为参数运行它:
python3 /path/to/dirlists.py /path/to/maindirectory
Run Code Online (Sandbox Code Playgroud)如前所述,该脚本将一个 list.txt 添加到所有subdirs。如果您还需要或希望在目录的主(根)目录中有一个列表,请提及。
递归列出(遍历)目录中的所有目录:
python3 /path/to/dirlists.py /path/to/maindirectory
Run Code Online (Sandbox Code Playgroud)为每个人创建一个内容列表:
os.listdir(dr)
Run Code Online (Sandbox Code Playgroud)打开(必要时创建)文本文件并写入列出的内容,不包括可能的早期文件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)
注意缩进,将替换放置在完全相同的位置