幫我修改代碼,我還需要它的内容表名稱寫在相應内容的前面,并且每一行都要循環加上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) # copy files and rename 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"{today.strftime('%Y%m%d')}_{file_name}" shutil.copy(file_path, os.path.join(dst_folder, new_file_name)) # write file contents with corresponding file names 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"{new_file_name[:-4]},{file_content}") 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'.join(file_contents))
时间: 2023-12-12 15:04:33 浏览: 102
Python实现删除文件中含“指定内容”的行示例
5星 · 资源好评率100%
請確認一下,我的理解是您希望在每一行前面加上文件名稱,並將最後生成的文件名稱改為 "汇总文档.txt"。如果我有誤解請告訴我,我會再次修改。
```
import os
import shutil
from datetime import date
src_folder = r"Y:\iplas\Robot_Log\SMT"
dst_folder = r"D:\測試log"
today = date.today()
# 創建目標文件夾(如果不存在)
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"{today.strftime('%Y%m%d')}_{file_name}"
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_name[:-4]},{file_content}")
except Exception as e:
print(f"Error reading file {file_name}: {e}")
# 將文件名稱改為"汇总文档.txt"並寫入文件
with open(os.path.join(dst_folder, '汇总文档.txt'), 'w', encoding='gbk') as f:
f.write('\n'.join(file_contents))
```
阅读全文