Update 更新文件名.py

This commit is contained in:
frxz751113
2024-09-15 10:48:25 +08:00
committed by GitHub
parent 1873e0e66a
commit 9f9634ef71
+14 -11
View File
@@ -21,30 +21,33 @@ def rename_files():
all_files = os.listdir(os.getcwd()) all_files = os.listdir(os.getcwd())
# 要重命名的文件名列表(初始文件名) # 要重命名的文件名列表(初始文件名)
initial_filenames = ['综合源.m3u', '组播优选.txt', '综合源.txt'] initial_filenames = ['综合源.m3u', '组播优选.txt', '综合源.txt'] #, '综合源.m3u', '组播优选.txt', '网络收集.txt'
for old_filename in all_files: for old_filename in all_files:
# 检查文件是否是需要重命名的文件(根据初始文件名判断) # 检查文件是否是需要重命名的文件(根据初始文件名判断)
if any(old_filename.endswith(init_filename) for init_filename in initial_filenames): if any(old_filename.endswith(init_filename) for init_filename in initial_filenames):
renamed_exists = False if last_update_time and old_filename.startswith(f"{last_update_time}"):
for f in all_files: # 如果只有上次重命名过的文件,用当前时间替换上次时间进行重命名
if f.startswith(f"{last_update_time}{old_filename}"): original_filename_after_last_time = old_filename[len(last_update_time):]
renamed_exists = True new_filename = f"{current_date}{original_filename_after_last_time}"
break full_old_path = os.path.join(os.getcwd(), old_filename)
if renamed_exists: full_new_path = os.path.join(os.getcwd(), new_filename)
os.rename(full_old_path, full_new_path)
print(f"Renamed {old_filename} to {new_filename}")
else:
# 如果同时存在初始文件名和重命名过的文件,删除重命名过的文件 # 如果同时存在初始文件名和重命名过的文件,删除重命名过的文件
if any(f.endswith(old_filename) and f.startswith(last_update_time) for f in all_files):
full_old_path = os.path.join(os.getcwd(), f"{last_update_time}{old_filename}") full_old_path = os.path.join(os.getcwd(), f"{last_update_time}{old_filename}")
if os.path.exists(full_old_path):
os.remove(full_old_path) os.remove(full_old_path)
print(f"Deleted {f'{last_update_time}{old_filename}'}") print(f"Deleted {f'{last_update_time}{old_filename}'}")
else: # 对初始文件名文件进行重命名
# 如果只有初始文件名的文件,进行重命名
new_filename = f"{current_date}{old_filename}" new_filename = f"{current_date}{old_filename}"
full_old_path = os.path.join(os.getcwd(), old_filename) full_old_path = os.path.join(os.getcwd(), old_filename)
full_new_path = os.path.join(os.getcwd(), new_filename) full_new_path = os.path.join(os.getcwd(), new_filename)
os.rename(full_old_path, full_new_path) os.rename(full_old_path, full_new_path)
print(f"Renamed {old_filename} to {new_filename}") print(f"Renamed {old_filename} to {new_filename}")
else:
continue
# 更新记录时间的文件 # 更新记录时间的文件
with open(time_file_path, 'w') as time_file: with open(time_file_path, 'w') as time_file:
time_file.write(current_date) time_file.write(current_date)