我在读取文件、处理其字符串并保存到 UTF-8 文件时遇到问题。
这是代码:
try:
filehandle = open(filename,"r")
except:
print("Could not open file " + filename)
quit()
text = filehandle.read()
filehandle.close()
然后我对变量文本进行一些处理。
接着
try:
writer = open(output,"w")
except:
print("Could not open file " + output)
quit()
#data = text.decode("iso 8859-15")
#writer.write(data.encode("UTF-8"))
writer.write(text)
writer.close()
这完美地输出了文件,但根据我的编辑器,它在 iso 8859-15 中这样做。由于同一个编辑器将输入文件(在变量文件名中)识别为 UTF-8,我不知道为什么会发生这种情况。据我的研究表明,注释行应该可以解决问题。但是,当我使用这些行时,生成的文件主要在特殊字符中出现乱码,带有波浪号的单词作为文本是西班牙语。我真的很感激任何帮助,因为我很难过......
使用带有 encoding
参数的 open
在程序的 I/O 边界处处理与 Unicode 往来的文本。确保使用正在读取的文件的(希望记录在案的)编码。默认编码因操作系统而异(具体而言,locale.getpreferredencoding(False)
是使用的编码),因此我建议始终明确使用 encoding
参数以实现可移植性和清晰性(以下 Python 3 语法):
with open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with open(filename, 'w', encoding='utf8') as f:
f.write(text)
如果仍在使用 Python 2 或为了兼容 Python 2/3,io
模块会使用与 Python 3 的 open
相同的语义实现 open
,并且在两个版本中都存在:
import io
with io.open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with io.open(filename, 'w', encoding='utf8') as f:
f.write(text)
你也可以通过下面的代码来打通它:
file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()
你不能使用 open 来做到这一点。使用编解码器。
当您使用 open 内置函数在 python 中打开文件时,您将始终以 ascii 读取/写入文件。要用 utf-8 写它,试试这个:
import codecs
file = codecs.open('data.txt','w','utf-8')
编码参数就是诀窍。
my_list = ['1', '2', '3', '4']
with open('test.txt', 'w', encoding='utf8') as file:
for i in my_list:
file.write(i + '\n')
errors=ignore
或errors=replace
传递给open()
...如果您不知道文件的编码。 :)io.open
要求写入 Unicode 字符串,而不是字节字符串。它对声明的编码进行编码。ascii
编解码器将字节字符串隐式转换回 Unicode,因此只要字符串只是 ASCII 就可以工作。这就是 Python 3 改变它的原因......它防止了“它有时会工作”,这是一个令人讨厌的错误。