In Python, is read() , or readlines() faster?

后端 未结 8 1642
醉酒成梦
醉酒成梦 2020-11-30 05:50

I want to read a huge file in my code. Is read() or readline() faster for this. How about the loop:

for line in fileHandle
8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 06:34

    The docs for readlines indicate there is an optional sizehint. Because it is so vague, it's easy to overlook, but I found this to often be the fastest way to read files. Use readlines(1), which hints one line, but in fact reads in about 4k or 8k worth of lines IIRC. This takes advantage of the OS buffering and reduces the number of calls somewhat without using an excessive amount of memory.

    You can experiment with different sizes of the sizehint, but I found 1 to be optimal on my platform when I was testing this

提交回复
热议问题