内存错误Python(巨大的文件更改)

2024-05-23 14:33:47 发布

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

我正在尝试将文件的行尾(EOL)从Windows更改为Linux,文件大小为50 GB,并写入同一个文件,下面是我的代码:

filename = "D:\AddressEvaluation\AddressStandardization\infu\InfutorFile.txt"
fileContents = open(filename,"r").read()
f = open(filename,"w", newline="\n")
f.write(fileContents)
f.close()

它给了我一个错误:

^{pr2}$

我错过什么了吗? 请帮忙?在


Tags: 文件代码txtlinuxwindowsopenfilenamegb
1条回答
网友
1楼 · 发布于 2024-05-23 14:33:47

这可能是因为文件的大小。(可能太大了)

一次将大文件读入内存通常会引发此错误。在

您可以通过使用以下代码逐行读取文件来处理此问题:

f1 = open(filename,"w", newline="\n")

with open('D:\AddressEvaluation\AddressStandardization\infu\InfutorFile.txt') as f:
    for fileContents in f:
        f1.write(fileContents)
f1.close()

这将解决MemoryError的问题。 您还可以查看Memory error due to the huge input file size

相关问题 更多 >