用Python处理大文本文件

2024-04-16 10:26:05 发布

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

基本的是我需要以每行为基础处理4gig文本文件。在

在f中使用.readline()或for line对内存很好,但是IO需要很长时间。我想用屈服点之类的东西,但那(我想)会砍掉线条。在

可能的答案:

^{1}$
Read until EOF using readline() and return a list containing the lines

thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Objects implementing a file-like interface may choose to ignore sizehint if it cannot be implemented, or cannot be implemented efficiently.

没想到你能做到!在


Tags: thetoforreadreadlinelinebe基础
3条回答

只需迭代文件对象:

with open("filename") as f:
    for line in f:
        whatever

这将进行一些内部缓冲以提高性能。{{cd1}不能对cd1}文件进行迭代,因为这样做会更糟

如果您想以每行为单位执行某项操作,只需在file对象上循环:

f = open("w00t.txt")
for line in f:
    # do stuff

然而,以每行为单位执行任务可能会成为性能的实际瓶颈,所以也许您应该使用更好的块大小?例如,您可以做的是,读取4096个字节,找到以\n结尾的最后一行,对该部分进行处理,并将剩下的部分放在下一个块中。在

你总是能把台词拼凑起来吗?我的意思是当你可以打开同一个文件6次并进行迭代时,为什么要打开一个文件并一直迭代呢。 e、 g

a #is the first 1024 bytes
b #is the next 1024
#etcetc
f #is the last 1024 bytes

每个文件句柄运行在一个单独的进程中,我们开始用煤气做饭。只需记住正确处理行尾。在

相关问题 更多 >