首页 > 解决方案 > 如果文件太大,UTF8 转换需要很长时间并且会崩溃

问题描述

我编写了以下应该将文件转换为 UTF8 的 python 代码。它运行良好,但我注意到如果文件太大(在这种情况下,我们谈论的是 10GB 的文件!)程序崩溃!

一般来说,它似乎需要太多时间:9分钟转换一个2GB的文本文件:也许我可以让它更高效?我认为这是因为我首先读取整个文件然后保存它,可能是这样吗?

  import sys
  import codecs

  filename= sys.argv[1]
  with codecs.open(filename, 'r', encoding='iso-8859-1') as f:
    text = f.read()
  with codecs.open(filename, 'w', encoding='utf8') as f:
    f.write(text)

标签: pythoncharacter-encoding

解决方案


是的,这可能是因为您正在一行中读取整个文件。最好分段读取这个文件,将它们转换为 utf-8,然后将这些片段写入另一个文件。

import sys
import codecs

BLOCKSIZE = 1048576 # or some other, desired size in bytes

sourceFileName = sys.argv[1]
targetFileName = sourceFileName + '-converted'

with codecs.open(sourceFileName, "r", "iso-8859-1") as sourceFile:
    with codecs.open(targetFileName, "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents: break
            targetFile.write(contents)

我从这个问题中获取了代码(并对其进行了一些修改)


推荐阅读