gpt4 book ai didi

python - 更多Python主义 : prefix subdirectory with parent folder name?

转载 作者:太空宇宙 更新时间:2023-11-03 18:00:58 24 4
gpt4 key购买 nike

我正在清理一些文件夹。给定文件结构:

a/1
a/2
a/3
a/3/3_1
a/3/3_2

我想通过在第一级文件夹前添加父文件夹前缀来重命名第一级文件夹仅当它不包含任何子目录时,即输出:

a/a-1
a/a-2
a/3
a/3/3_1
a/3/3_2

我有以下代码来执行此操作:

root_dir = "./"
parent_path = os.path.abspath(root_dir)
parent_folder_name = os.path.abspath(root_dir).split('/')[-1]

dirs = []
for entry in os.listdir(root_dir):
absolute_path = parent_path + "/" + entry
if os.path.isdir(absolute_path) and entry[0] != ".":
dirs.append(absolute_path)

for first_level_dir in dirs:
# travers each directory in root directory
skip_dir = False

subdirs = os.walk(first_level_dir).next()[1]
if len(subdirs) == 0
volume_folder_name = first_level_dir.split("/")[-1]
new_dir_name = (parent_path + "/" + parent_folder_name + "-" + volume_folder_name)
os.rename(first_level_dir, new_dir_name)

代码可以工作,但看起来非常冗长。有没有更Pythonic的方法来做到这一点?

最佳答案

为了使代码更具可读性,请提取 has_subdir() 函数:

from pathlib import Path

def has_subdir(path):
return any(p.is_dir() for p in path.iterdir())

root = Path().resolve()
dirs = [p for p in root.iterdir() if p.is_dir() and not has_subdir(p)]
for oldpath in dirs:
newname = '{}-{}'.format(oldpath.parent.name, oldpath.name)
oldpath.rename(oldpath.with_name(newname))

关于python - 更多Python主义 : prefix subdirectory with parent folder name?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27683406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com