【问题标题】:Convert from ANSI to UTF-8从 ANSI 转换为 UTF-8
【发布时间】:2015-10-06 21:29:12
【问题描述】:


我有大约 600,000 个文件以 ANSI 编码,我想将它们转换为 UTF-8。我可以在 NOTEPAD++ 中单独执行此操作,但对于 600,000 个文件,我无法执行此操作。我可以在 RPython 中执行此操作吗?

我找到了这个链接,但是Python 脚​​本没有运行: notepad++ converting ansi encoded file to utf-8

【问题讨论】:

  • “ANSI”是指“Windows-1252”编码?
  • @KlausD。它在 Notepad++ 中显示为 ANSI
  • 请注意,“lakh”不是标准(美国/英国 == 国际)英语中的单词。世界角落以外的许多人都不知道“十万”是什么。
  • ANSI 不是编码。什么是“十万”?
  • @hd1 lakh 是南亚单词,表示 100k。

标签: python r notepad++


【解决方案1】:

您为什么不读取文件并将其写入为 UTF-8?你可以在 Python 中做到这一点。

#to support encodings
import codecs

#read input file
with codecs.open(path, 'r', encoding = 'utf8') as file:
  lines = file.read()

#write output file
with codecs.open(path, 'w', encoding = 'utf8') as file:
  file.write(lines)

【讨论】:

  • 不会以 utf-8 格式读取不同的代码页会丢失一些字符吗? (虽然在写入另一个代码页之前您必须使用正确的代码页阅读)?
  • 来自 Python 规范:注意:文件总是以二进制模式打开,即使没有指定二进制模式。这样做是为了避免由于使用 8 位值进行编码而导致的数据丢失。这意味着在读写时不会自动转换 '\n'。
  • 我必须将读取编码更改为“cp1252”才能让它为我工作。它仍然以 UTF-8 打开,否则在遇到混合文件时给我一个错误:'utf-8' codec can't decode byte 0x92
【解决方案2】:

我很欣赏这是一个老问题,但最近刚刚解决了一个类似的问题,我想我会分享我的解决方案。

我有一个程序正在准备一个文件,我需要将它导入到 sqlite3 数据库中,但文本文件始终是“ANSI”并且 sqlite3 需要 UTF-8。

ANSI 编码在 python 中被识别为“mbcs”,因此我使用的代码,抄袭了我发现的其他内容:

blockSize = 1048576
with codecs.open("your ANSI source file.txt","r",encoding="mbcs") as sourceFile:
    with codecs.open("Your UTF-8 output file.txt","w",encoding="UTF-8") as targetFile:
        while True:
            contents = sourceFile.read(blockSize)
            if not contents:
                break
            targetFile.write(contents)

以下链接包含一些关于我在研究中发现的编码类型的信息

https://docs.python.org/2.4/lib/standard-encodings.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 2014-07-02
    • 2019-02-10
    • 1970-01-01
    • 2014-01-27
    • 2011-05-20
    • 2013-12-14
    相关资源
    最近更新 更多