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

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)

  • 对于任何人来说,请注意,对于Python3`open()`和`io,open()`是相同的.只需使用`open()`.查看帮助(打开),您将看到它与io.open()相同 - 甚至标题显示在模块io中打开内置函数的帮助. (9认同)
  • 我完全按照你告诉我的方式做了.与其他建议相同的错误 (4认同)

小智 7

您也可以通过以下代码了解它:

file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()
Run Code Online (Sandbox Code Playgroud)


Fer*_*ves 5

你不能使用 open 来做到这一点。使用编解码器。

当您使用 open 内置函数在 python 中打开文件时,您将始终以 ascii 格式读/写该文件。要以 utf-8 编写,请尝试以下操作:

import codecs
file = codecs.open('data.txt','w','utf-8')
Run Code Online (Sandbox Code Playgroud)

  • 尝试这个,我得到一个错误:UnicodeDecodeError:'utf8'编解码器无法解码位置57中的字节0xe9:无效的连续字节 (2认同)