[英]Find leaf folders that aren't hidden folders
我在最下面的文件夾中有一個包含一些 epub 和 json 文件的文件夾結構(不包括.ts
文件夾)。 我通過使用其他一些json
文件創建一個.ts
文件夾,將標簽從 json 文件導出到標簽空間。 我已經處理了部分文件,現在我想找到路徑中沒有.ts
文件夾的葉子文件夾,以找到剩余的文件,而不必處理其他文件兩次。
所以對於這個例子,我只想為文件夾t5
做一些事情:
test
├── t1
│ ├── t2
│ │ └── t5
│ └── t3
│ └── .ts
└── .ts
└── t4
這是我嘗試過的:
def process_files_in_leaf_subdirectories(dir: str) -> None:
dirs = []
for root, subdirs, filenames in os.walk(dir):
if subdirs or '.ts' in root:
continue
dirs.append(root)
return dirs
def test_process_files_in_leaf_subdirectories():
os.makedirs('tmp/t1/t2/t5', exist_ok=True)
os.makedirs('tmp/t1/t3/.ts', exist_ok=True)
os.makedirs('tmp/.ts/t4', exist_ok=True)
assert get_files_in_leaf_subdirectories('tmp') == ['tmp/t1/t2/t5']
shutil.rmtree('tmp')
由於您想找到葉子目錄,而不計算.ts
目錄 - 只需遞歸訪問非隱藏路徑並生成沒有任何子目錄的目錄就足夠了。
對於 python 中的此類路徑操作,我建議改用pathlib.Path
。
這是生成沒有任何子目錄的葉目錄的生成器:
import pathlib
def find_leaf_dir_gen(root_path: pathlib.Path) -> pathlib.Path:
# filter subdirectories
child_dirs = [path for path in root_path.iterdir() if path.is_dir()]
# if no child_dir, yield & return
if not child_dirs:
yield root_path
return
# otherwise iter tru subdir
for path in child_dirs:
# ignore hidden dir
if path.stem[0] == ".":
continue
# step in and recursive yield
yield from find_leaf_dir_gen(path)
示例使用
>>> leaves = list(find_leaf_dir_gen(ROOT))
>>> leaves
[WindowsPath('X:/test/t1/t2/t5'), WindowsPath('X:/test/t1/t3/t6')]
>>> for path in leaves:
... ts_path = path.joinpath(".ts")
... ts_path.mkdir()
測試目錄結構 - 之前:
X:\TEST
├─.ts
│ └─t4
└─t1
├─t2
│ └─t5
└─t3
├─.ts
└─t6
后:
X:\TEST
├─.ts
│ └─t4
└─t1
├─t2
│ └─t5
│ └─.ts
└─t3
├─.ts
└─t6
└─.ts
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.