#该脚本用于将所有日期格式调整为YYYYMMDD格式,例如:20230101
#date:20230609
#mail:[email protected]
import os
import re
import datetime
# 输入要操作的目录
dir_path = "/mnt/e/date_rename"
target_strs = ["20232023.", "20232023-","20232023_"]
# 获取当前年份
current_year = datetime.datetime.now().year
# 处理日期格式为x月xx日的文件名
for filename in os.listdir(dir_path):
full_path = os.path.join(dir_path, filename)
if os.path.isfile(full_path) or os.path.isdir(full_path):
new_name = re.sub(r'([1-9]|1[0-2])月([1-9]|[1-2][0-9]|3[0-1])', rf'{current_year}\g<1>\g<2>', filename)
os.rename(full_path, os.path.join(dir_path, new_name))
# 处理日期格式为x.xx、x-xx、0x-xx、0xxx的文件名,以及202363格式
for filename in os.listdir(dir_path):
full_path = os.path.join(dir_path, filename)
if os.path.isfile(full_path) or os.path.isdir(full_path):
# 使用正则表达式将日期格式转换为“2023xxxx”的形式
new_name = re.sub(r'(?<![0-9])([0-9]{1,2})[.-]?([0-9]{1,2})(?![0-9])', rf'{current_year}\1\2', filename)
new_name = re.sub(r'(?<![0-9])([0-9]{1,2})[._]?([0-9]{1,2})(?![0-9])', rf'{current_year}\1\2', filename)
new_name = re.sub(r'(?<![0-9])0([0-9]{3})(?![0-9])', rf'{current_year}\1', new_name)
new_name = re.sub(r'(?<!\d)(\d{4})(\d{2})(\d{2})(?!\d)', r'\1\2\3', new_name)
os.rename(full_path, os.path.join(dir_path, new_name))
# 遍历该目录下所有文件夹
for folder_name in os.listdir(dir_path):
# 判断是否为文件夹
if os.path.isdir(os.path.join(dir_path, folder_name)):
# 判断文件夹名称中是否包含目标字符串
for target_str in target_strs:
if target_str in folder_name:
# 将目标字符串替换为空
new_name = folder_name.replace(target_str, "")
# 使用os.rename方法进行修改
os.rename(os.path.join(dir_path, folder_name), os.path.join(dir_path, new_name))
break # 跳出内层循环,处理下一个文件夹
#将202363转换为20230603
# 定义正则表达式匹配模式
pattern = re.compile(r'\d{4}\d{0,1}\d{0,1}\d{0,1}')
# 遍历该目录下所有文件夹
for folder_name in os.listdir(dir_path):
# 判断是否为文件夹
#if os.path.isdir(os.path.join(dir_path, folder_name)):
# 匹配目标字符串
match = pattern.search(folder_name)
if match:
# 获取匹配到的字符串
target_str = match.group()
# 将目标字符串中的非必要零替换为空
if len(target_str) != 6:
continue
new_str = target_str.lstrip("0")
# 将新格式日期字符串按照 YYYY-MM-DD 格式进行重新格式化
new_str = "".join([new_str[0:4], new_str[4:5].rjust(2, '0'), new_str[5:].rjust(2, '0')])
# 使用re.sub方法进行替换
new_name = re.sub(pattern, new_str, folder_name)
# 重命名该文件夹
os.rename(os.path.join(dir_path, folder_name), os.path.join(dir_path, new_name))
#将2023512转换为20230512
pattern = re.compile(r'\d{4}[01]?\d')
for folder_name in os.listdir(dir_path):
# 判断是否为文件夹
#if os.path.isdir(os.path.join(dir_path, folder_name)):
# 匹配目标字符串
match = pattern.search(folder_name)
if match:
# 获取匹配到的字符串
target_str = match.group()
# 判断该日期格式是否为 YYYYM 格式
if len(target_str) != 5:
continue
# 将新格式日期字符串按照 YYYYMM 格式进行重新格式化
new_str = "".join([target_str[0:4], target_str[4:].rjust(2, '0')])
# 使用re.sub方法进行替换
new_name = re.sub(pattern, new_str, folder_name)
# 重命名该文件夹
os.rename(os.path.join(dir_path, folder_name), os.path.join(dir_path, new_name))
PHP脚本,用于统一文件名中日期格式
猜你喜欢
转载自blog.csdn.net/m0_55877125/article/details/131204930
今日推荐
周排行