如何在内存有问题的大型文本文件中编辑一行



所以我有一个很大的文件,有几千行,看起来像这样:

this a line
some line are long like this one
some are very longgggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg like this
some are even longer than that
some are small like the line after this one
a
and this continue on for a few more thousand line

例如,我想编辑第4724行,只是从它的当前值this is a line that im using as an exampleI want to edit the line into this的一个随机行。我怎么能在python中做到这一点。如果你需要更多信息,请在评论中问我。

编辑:这个文件大约是300KB,是的,我尝试过readlines(),它只返回整个文件的1/3。所以我说内存是个问题

根据文件的大小,在注释中给定为100KB,您应该只是天真地阅读文件并更改有问题的行。

LINE_TO_CHANGE=4724
with open('my_file.txt') as f:
lines = f.readlines()
lines[LINE_TO_CHANGE - 1] = 'edited linen'
with open('my_file.txt', 'w') as f:
f.writelines(lines)

最新更新