繁体   English   中英

合并 Python 中的多个文本文件时出现编码错误

[英]Encoding Error While Merging Multiple Text Files in Python

我想使用 python3 合并多个文件。 所有文件都在一个以 .txt 作为扩展名的文件夹中。 在文件夹中,有以特殊字符开头的文件,如dot (.)braces()等。代码和数据集位于不同的文件夹中。 请帮忙。

我尝试过的如下:

#encoding:utf-8
import os
from pprint import pprint
path = 'F:/abc/intt'
file_names = os.listdir(path)
with open('F://hi//Datasets//megef_fil.txt', 'w', encoding = 'utf-8') as outfile:
   for fname in file_names:
       with open(os.path.join(path,fname)) as infile:
          for line in infile:
              outfile.write(line)

我面临的跟踪错误是这样的。

文件“C:\Users\Shanky\AppData\Local\Programs\Python\Python37\lib\encodings\cp1252.py”,第 23 行,解码返回 codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError :'charmap'编解码器无法解码 position 31 中的字节 0x8d:字符映射到

我绝对不知道我哪里出错了。 请帮我解决这个问题。 任何帮助表示赞赏。

似乎您以字节为单位读取了 inerfile,但编码不正确,请尝试执行以下操作:


with open(os.path.join(path,fname), mode="r", encoding="utf-8") as infile:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM