import os
import zipfile
from datetime import datetime
import shutil
# 获取当前日期
current_date = datetime.now().strftime('%Y%m%d')
# 文件路径
input_dir = './inputfiles'
# 遍历目录中的文件
for file_name in os.listdir(input_dir):
file_path = os.path.join(input_dir, file_name)
# 处理CSV文件
if file_name.endswith('.csv'):
# 替换文件名中的日期为当前日期
new_file_name = file_name.split('-')[0] + f'-{current_date}.csv'
new_file_path = os.path.join(input_dir, new_file_name)
os.rename(file_path, new_file_path)
# 处理ZIP文件
elif file_name.endswith('.zip'):
with zipfile.ZipFile(file_path, 'r') as zip_ref:
# 提取ZIP文件内容到临时目录
zip_ref.extractall(input_dir)
# 遍历解压后的文件,找到需要修改的文件名
extracted_dir = os.path.join(input_dir, 'opt', 'report')
for extracted_file_name in os.listdir(extracted_dir):
if extracted_file_name.endswith('.csv'):
# 替换文件名中的日期为当前日期
new_extracted_file_name = extracted_file_name.split('-')[0] + f'-{current_date}.csv'
extracted_file_path = os.path.join(extracted_dir, extracted_file_name)
new_extracted_file_path = os.path.join(extracted_dir, new_extracted_file_name)
os.rename(extracted_file_path, new_extracted_file_path)
# 重新创建ZIP文件
new_zip_file_name = file_name.split('-')[0] + f'-{current_date}.zip'
new_zip_file_path = os.path.join(input_dir, new_zip_file_name)
with zipfile.ZipFile(new_zip_file_path, 'w') as zip_ref:
for root, _, files in os.walk(os.path.join(input_dir, 'opt')):
for file in files:
zip_ref.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), input_dir))
# 删除解压后的文件夹
shutil.rmtree(os.path.join(input_dir, 'opt'))
# 删除旧的ZIP文件
os.remove(file_path)