還是報錯,請幫忙修改完整可使用代碼.Traceback (most recent call last): File "D:\pythonProject\venv\Lib\site-packages\pandas\io\common.py", line 25, in <module> f.write(t.read()) File "D:\Program Files\Python310\lib\codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa4 in position 1: invalid start byteD代碼如下: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: # 如果是今天生成的 txt 文件,复制到本地路径 shutil.copy(file_path, os.path.join(dst_folder, file_name)) # 将本地路径中所有 txt 文件的内容汇总到一个文档 with open('汇总文档.txt', 'w', encoding='utf-8') as f: for file_name in os.listdir(dst_folder): if file_name.endswith('.txt'): with open(os.path.join(dst_folder, file_name), 'r', encoding='utf-8') as t: f.write(t.read())
时间: 2024-01-11 11:02:50 浏览: 140
这个错误是因为在读取文件时使用了错误的编码格式。你可以尝试修改代码中 `with open(os.path.join(dst_folder, file_name), 'r', encoding='utf-8') as t:` 这一行的编码格式,比如使用 `gbk` 编码格式。
修改后的代码如下:
```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:
# 如果是今天生成的 txt 文件,复制到本地路径
shutil.copy(file_path, os.path.join(dst_folder, file_name))
# 将本地路径中所有 txt 文件的内容汇总到一个文档
with open('汇总文档.txt', 'w', encoding='gbk') as f:
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:
f.write(t.read())
```
注意:以上代码中修改了第二个 `with open()` 函数的编码格式为 `gbk`,用于匹配文件的实际编码格式,你也可以根据实际情况修改。
阅读全文