Update 更新文件名.py

This commit is contained in:
frxz751113
2024-09-15 13:49:01 +08:00
committed by GitHub
parent c1e8d8ada8
commit a2ad88e3d6
+32 -17
View File
@@ -1,30 +1,45 @@
import datetime import datetime
import os import os
# 获取当前日期时间 # 记录时间的文件路径
now = datetime.datetime.now() time_file_path = '上次更新时间.txt'
current_date = now.strftime("%m%d")
# 要重命名的纯中文文件名列表 def rename_files():
chinese_filenames = ['综合源.m3u', '组播优选.txt', '综合源.txt'] try:
# 尝试读取上次记录的时间
with open(time_file_path, 'r') as time_file:
last_update_time = time_file.read()
print(f"Last update time read: {last_update_time}")
except FileNotFoundError:
last_update_time = ""
# 获取当前目录下的所有文件 # 获取当前日期时间
all_files = os.listdir(os.getcwd()) now = datetime.datetime.now()
current_date = now.strftime("%m%d%H%M")
# 删除以数字加中文形式命名的文件 # 获取当前目录下的所有文件
for old_filename in all_files: all_files = os.listdir(os.getcwd())
if any(char.isdigit() for char in old_filename) and (old_filename.endswith('.txt') or old_filename.endswith('.m3u')):
full_old_path = os.path.join(os.getcwd(), old_filename)
if os.path.exists(full_old_path):
os.remove(full_old_path)
print(f"Deleted {old_filename}")
# 重命名纯中文文件名的文件 # 重命名的文件名列表(初始文件名)
for old_filename in all_files: initial_filenames = ['综合源.txt', '组播优选.txt', '网络收集.txt']
if any(old_filename.endswith(init_filename) for init_filename in chinese_filenames):
for old_filename in all_files:
# 检查文件是否是需要重命名的文件(根据初始文件名判断)
if any(old_filename.endswith(init_filename) for init_filename in initial_filenames):
if last_update_time and old_filename.startswith(f"{last_update_time}"):
# 如果文件名已包含上次时间,提取原文件名部分并替换为当前时间
original_filename = old_filename[len(last_update_time):]
new_filename = f"{current_date}{original_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}")
# 更新记录时间的文件
with open(time_file_path, 'w') as time_file:
time_file.write(current_date)
rename_files()