python - 如果文件太大,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)
解决方案
是的,这可能是因为您正在一行中读取整个文件。最好分段读取这个文件,将它们转换为 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)
我从这个问题中获取了代码(并对其进行了一些修改)
推荐阅读
- r - 使用 tesseract 进行 OCR 后提取一段文本
- android-studio - 单击每个列表项,如何在另一个活动中播放该项目的歌曲?
- webhooks - Google Cloud Build 的 POST 正文 - Webhook 触发器
- sql - 如何根据具有更新值的列过滤源表中的更新?只需要为一个特定的列更新具有新值的行
- html - 无法分别添加滚动到内容和侧栏 div
- excel - 在上下文单元菜单中放置一个按钮
- regex - 正则表达式积极看待记事本++
- java - 简单的OOPS演示,卡住了for循环的功能及其在main方法中的作用
- php - 试图让 icu4c 版本 64 在 Mac Catalina 上与 PHP 5.6 一起使用
- java - Java 编码 - 损坏的法语字符