gpt4 book ai didi

Python - 读取和删除文件的顶行而不将其加载到内存中

转载 作者:太空宇宙 更新时间:2023-11-03 18:34:01 24 4
gpt4 key购买 nike

我需要对每个大约 150 MB 的文本文件进行合并排序,总计约 5GB

问题是我无法使用 readlines() 进行合并排序,因为最后一步需要将 5GB 加载到内存中,并且只需要

for line1 in file1, line2 in file2:
while( line1 & line2 )...

命令,我无法告诉python只获取文件1的下一行,并保留文件2的行,因此无法进行合并排序

我读到了一些关于在 readlines() 上将 readbuffer 设置得非常低的内容,仅将一行加载到内存中,但随后我无法从文件中删除第一行

是否有任何其他内存有效的方法来仅获取文件的第一行并删除它,或者是否有可用的函数可以将两个文本文件合并排序?

最佳答案

command, i can't tell python to only get the next line of file 1, and keep the line of file 2, and thus are unable to make a merge sort

不,你可以。

line1 = file1.readline()
line2 = file2.readline()
while file1_not_at_end and file2_not_at_end:
if line1 < line2:
file3.write(line1)
line1 = file1.readline()
else:
file3.write(line2)
line2 = file2.readline()

# merge file 1 into file 3
# merge file 2 into file 3

关于Python - 读取和删除文件的顶行而不将其加载到内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21910889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com