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

2024-04-26 13:11:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我在读取文件、处理其字符串并保存到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,所以我不知道为什么会发生这种情况。据我的研究表明,注释行应该可以解决这个问题。然而,当我使用这些行时,生成的文件主要在特殊字符中有乱七八糟的内容,文本中带有颚化符的单词是西班牙语。我真的很感激任何帮助,因为我被难住了。。。。


Tags: 文件textclosenotopenfilenamequitutf
3条回答

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

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

使用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)

编辑:现在建议使用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。使用编解码器。

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

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

相关问题 更多 >