Python从文件读取并保存到UTF-8

我从文件读取,处理string并保存到UTF-8文件时遇到问题。

这里是代码:

try: filehandle = open(filename,"r") except: print("Could not open file " + filename) quit() text = filehandle.read() filehandle.close() 

然后我对variables文本做一些处理。

接着

 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根据我的编辑器。 由于同一编辑器将input文件(在variables文件名中)识别为UTF-8,我不知道为什么发生这种情况。 至于我的研究表明,评论线应该解决这个问题。 但是,当我使用这些行时,生成的文件主要是特殊字符中的乱码,带有波浪号的文字是西class牙文。 我真的很感激任何帮助,因为我难倒….

在使用codecs模块的程序的I / O边界处处理Unicode和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) 

编辑:现在推荐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) 

你不能用open打开。 使用编解码器。

当你使用打开的内置函数在python中打开一个文件时,你将总是以ascii读/写这个文件。 要用utf-8编写它,请尝试以下操作:

 import codecs file = codecs.open('data.txt','w','utf-8') 

你也可以通过下面的代码来完成:

 file=open(completefilepath,'r',encoding='utf8',errors="ignore") file.read()