aar*_*ich 66 python utf-8 python-2.7
我在读取文件,处理其字符串并保存为UTF-8文件时遇到问题.
这是代码:
try:
filehandle = open(filename,"r")
except:
print("Could not open file " + filename)
quit()
text = filehandle.read()
filehandle.close()
Run Code Online (Sandbox Code Playgroud)
然后我对变量文本进行一些处理.
然后
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()
Run Code Online (Sandbox Code Playgroud)
这完全输出文件,但根据我的编辑,它在iso 8859-15中这样做.由于同一编辑器将输入文件(在变量文件名中)识别为UTF-8,我不知道为什么会发生这种情况.就我的研究表明,评论的行应该可以解决问题.但是,当我使用这些行时,生成的文件主要是特殊字符的乱码,带有波浪号的文字是西班牙语.因为我难过,我真的很感激任何帮助....
Mar*_*nen 165
使用codecs
模块在程序的I/O边界处理与Unicode之间的文本:
import codecs
with codecs.open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with codecs.open(filename, 'w', encoding='utf8') as f:
f.write(text)
Run Code Online (Sandbox Code Playgroud)
编辑:io
现在推荐使用该模块而不是编解码器,并且与Python 3的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)
Run Code Online (Sandbox Code Playgroud)
小智 7
您也可以通过以下代码了解它:
file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()
Run Code Online (Sandbox Code Playgroud)
你不能使用 open 来做到这一点。使用编解码器。
当您使用 open 内置函数在 python 中打开文件时,您将始终以 ascii 格式读/写该文件。要以 utf-8 编写,请尝试以下操作:
import codecs
file = codecs.open('data.txt','w','utf-8')
Run Code Online (Sandbox Code Playgroud)