請你幫我修改,我需要寫入的表名稱不是在每個内容的最後面,我需要卸載每個内容相應加載每行後面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"{file_name[:-4]}_{today.strftime('%Y%m%d')}.txt" 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"{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'.join(file_contents))完整代碼
时间: 2023-12-12 11:04:33 浏览: 72
以下是修改后的代码,根据您的需求将表名移到每个内容的前面:
```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)
# 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))
```
修改后的代码中,将新文件名的日期部分放在了前面,通过 `{}` 和 `format` 方法将文件名和内容拼接成一行,然后将其添加到 `file_contents` 列表中。在写入汇总文档时,通过逗号将表名和内容分隔开,保证了表名在每个内容的前面。
阅读全文