[Python] 纯文本查看 复制代码 from pathlib import Path
def rename_files(dir_path: str, ext_fmt: str, new_name_prefix: str, sort_by=None):
root = Path(dir_path)
if not root.is_dir():
raise "directory path error!"
files_to_rename = []
for file in root.iterdir():
if file.suffix == ext_fmt:
tmp_name = file.parent / f'{file.name}._tmp'
file.rename(tmp_name)
files_to_rename.append(tmp_name)
# 如果对文件排序有要求 可以在这里做
# 如按照最后修改时间从晚到早排序
# 文件相关属性 可以参考 https://docs.python.org/zh-cn/3/library/os.html#os.stat_result
if sort_by == 'modify_time_dsc':
files_to_rename.sort(key=lambda x: x.stat().st_mtime_ns, reverse=True)
elif sort_by == 'modify_time_asc':
files_to_rename.sort(key=lambda x: x.stat().st_mtime_ns)
# 按照文件大小排序
elif sort_by == 'size_asc':
files_to_rename.sort(key=lambda x: x.stat().st_size)
elif sort_by == 'size_dsc':
files_to_rename.sort(key=lambda x: x.stat().st_size, reverse=True)
for i, file in enumerate(files_to_rename):
file.rename(file.parent / f'{new_name_prefix}{i + 1}{ext_fmt}')
pass
if __name__ == '__main__':
dir_path = './log'
# 按修改时间 从晚到早
rename_files(dir_path, ext_fmt='.log', new_name_prefix='mylog', sort_by='modify_time_dsc')
# 按修改时间 从早到晚
rename_files(dir_path, ext_fmt='.log', new_name_prefix='mylog', sort_by='modify_time_asc')
# 按文件大小 从大到小
rename_files(dir_path, ext_fmt='.log', new_name_prefix='mylog', sort_by='size_dsc')
# 按文件大小 从小到大
rename_files(dir_path, ext_fmt='.log', new_name_prefix='mylog', sort_by='size_asc')
# 有更具体的排序要求 可以自己实现
|