我正在做一些文件夹清理工作。鉴于文件结构:
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 方法吗?
答案 0 :(得分:1)
为了使代码更具可读性,请提取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))