請你幫我修改代碼,我需要將每個TXT文件的文件名稱,需要寫在每個文檔内容的後面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, 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_contents.append(t.read()) with open(os.path.join(dst_folder, '汇总文档.txt'), 'w', encoding='gbk') as f: f.write('\n\n'.join(file_contents))
时间: 2023-12-12 15:03:29 浏览: 98
人工智能-项目实践-信息检索-检索文件系统,表格输出 每层的文件个数及层级
以下是修改后的代码,其中我添加了将文件名写入文档内容的代码:
```python
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:
# 将文件名写入文档内容
with open(file_path, 'a', encoding='gbk') as f:
f.write('\n' + file_name)
shutil.copy(file_path, os.path.join(dst_folder, 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_contents.append(t.read())
with open(os.path.join(dst_folder, '汇总文档.txt'), 'w', encoding='gbk') as f:
f.write('\n\n'.join(file_contents))
```
修改后的代码在每个文档的内容后面添加了文件名,并将其复制到目标文件夹中。在生成的汇总文档中,每个文档的内容之间仍然用两个换行符分隔。
阅读全文