繁体   English   中英

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

[英]Python reading from a file and saving to utf-8

我在读取文件、处理其字符串和保存到 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模块实现open的语义与 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)

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

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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM