68 lines
2.7 KiB
Python
68 lines
2.7 KiB
Python
import os
|
|
import time # 如需使用时间戳可引入
|
|
|
|
|
|
def add_suffix_to_files(directory, suffix="_image"):
|
|
"""
|
|
遍历指定目录下的所有文件,如果文件名中不包含指定后缀字符,则在文件名末尾添加该后缀。
|
|
如果新文件名已存在,会自动在文件名中插入序号以避免冲突。
|
|
|
|
:param directory: 要处理的文件夹路径
|
|
:param suffix: 要添加的后缀,默认为"_image"
|
|
"""
|
|
# 检查目录是否存在
|
|
if not os.path.isdir(directory):
|
|
print(f"错误:目录 '{directory}' 不存在。")
|
|
return
|
|
|
|
# 获取目录中的所有文件(不包含子目录)
|
|
all_files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
|
|
|
|
# 首先,找出所有已经包含后缀的文件,避免重复处理
|
|
files_to_rename = []
|
|
for filename in all_files:
|
|
name_part, ext_part = os.path.splitext(filename)
|
|
# 检查文件名主干中是否不包含后缀(不区分大小写)
|
|
if suffix.lower() not in name_part.lower():
|
|
files_to_rename.append(filename)
|
|
else:
|
|
print(f"⏭️ 跳过: {filename} (已包含后缀)")
|
|
|
|
# 遍历需要重命名的文件
|
|
for filename in files_to_rename:
|
|
file_path = os.path.join(directory, filename)
|
|
name_part, ext_part = os.path.splitext(filename)
|
|
|
|
# 构建基础新文件名
|
|
base_new_filename = f"{name_part}{suffix}{ext_part}"
|
|
base_new_filepath = os.path.join(directory, base_new_filename)
|
|
|
|
new_filename = base_new_filename
|
|
new_filepath = base_new_filepath
|
|
|
|
# 检查基础新文件名是否存在,如果存在则添加序号
|
|
counter = 1
|
|
while os.path.exists(new_filepath):
|
|
# 在主干和后缀之间插入序号,例如 "file_image_1.txt"
|
|
new_filename = f"{name_part}{suffix}_{counter}{ext_part}"
|
|
new_filepath = os.path.join(directory, new_filename)
|
|
counter += 1
|
|
|
|
# 执行重命名操作
|
|
try:
|
|
os.rename(file_path, new_filepath)
|
|
# 如果最终使用的文件名与基础新文件名不同,说明添加了序号
|
|
if new_filename != base_new_filename:
|
|
print(f"⚠️ 重命名 (冲突解决): {filename} -> {new_filename} (原名称 {base_new_filename} 已存在)")
|
|
else:
|
|
print(f"✅ 已重命名: {filename} -> {new_filename}")
|
|
except OSError as e:
|
|
print(f"❌ 重命名 {filename} 时出错: {e}")
|
|
|
|
print("--- 所有文件处理完成 ---")
|
|
|
|
|
|
# 使用示例
|
|
if __name__ == "__main__":
|
|
folder_path = r'R:\TYSAR-德清院\D-切片成果\TYSAR-条带模式(SM)\港口\切片结果整理'
|
|
add_suffix_to_files(folder_path) |