代碼報錯,請修改import os import shutil from datetime import date src_folder = r"Y:\iplas\Robot_Log\SMT" dst_folder = "D:\測試log" today = date.today() for file_name in os.listdir(src_folder): if file_name.endswith('.txt'): file_path = os.path.join(src_folder, file_name) if date.fromtimestamp(os.path.getmtime(file_path)) == today: shutil.copy(file_path, os.path.join(dst_folder, f"{file_name},{file_name}")) file_contents = [] for file_name in os.listdir(dst_folder): if file_name.endswith('.txt'): with open(os.path.join(dst_folder, file_name), 'r', encoding='gbk') as t: file_content = t.read().strip() file_contents.append(f"{file_content},{file_name}") with open(os.path.join(dst_folder, '汇总文档.txt'), 'w', encoding='gbk') as f: f.write('\n\n'.join(file_contents))
时间: 2023-12-12 09:03:29 浏览: 105
src.zip_python_python 文件
请尝试使用以下代码,它会在文件名中添加当天日期,并且在复制文件时会创建目标文件夹(如果不存在),还会在文件读取时处理异常情况:
```
import os
import shutil
from datetime import date
src_folder = r"Y:\iplas\Robot_Log\SMT"
dst_folder = r"D:\測試log"
today = date.today()
# create target folder if it does not exist
if not os.path.exists(dst_folder):
os.makedirs(dst_folder)
for file_name in os.listdir(src_folder):
if file_name.endswith('.txt'):
file_path = os.path.join(src_folder, file_name)
if date.fromtimestamp(os.path.getmtime(file_path)) == today:
new_file_name = f"{file_name[:-4]}_{today.strftime('%Y%m%d')}.txt"
shutil.copy(file_path, os.path.join(dst_folder, new_file_name))
file_contents = []
for file_name in os.listdir(dst_folder):
if file_name.endswith('.txt'):
try:
with open(os.path.join(dst_folder, file_name), 'r', encoding='gbk') as t:
file_content = t.read().strip()
file_contents.append(f"{file_content},{file_name}")
except Exception as e:
print(f"Error reading file {file_name}: {e}")
with open(os.path.join(dst_folder, '汇总文档.txt'), 'w', encoding='gbk') as f:
f.write('\n\n'.join(file_contents))
```
阅读全文