import os标签:underscore,name,文件夹,file,path,input,输入,下划线 From: https://www.cnblogs.com/zly324/p/17791145.html
def rename_files_in_directory(directory_path, underscore_input):
try:
# 如果是范围输入,则解析范围的结束数字
if '-' in underscore_input:
start, end = map(int, underscore_input.split('-'))
underscore_count = end
else:
underscore_count = int(underscore_input)
# 获取文件夹中的所有文件
file_list = os.listdir(directory_path)
for file_name in file_list:
new_name = generate_new_name(file_name, underscore_count)
os.rename(os.path.join(directory_path, file_name), os.path.join(directory_path, new_name))
print(f"Renamed {file_name} to {new_name}")
except Exception as e:
print(f"Error: {e}")
def generate_new_name(file_name, underscore_count):
# 将文件名分割成部分
parts = file_name.split('_')
# 保留指定数量的下划线,其他的替换为空格
if len(parts) - 1 <= underscore_count:
return file_name
else:
# 保留前面的下划线部分
retained = '_'.join(parts[:underscore_count+1])
# 将后面的部分中的下划线全部替换为空格
replaced_with_space = ' '.join(parts[underscore_count+1:])
return f"{retained} {replaced_with_space}"
if __name__ == '__main__':
directory_path = input("请输入文件夹地址: ").strip()
underscore_input = input("请输入你想保留的下划线数量或范围 (例如: 1 或 1-3): ").strip()
rename_files_in_directory(directory_path, underscore_input)