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

后端 未结 8 1668
醉酒成梦
醉酒成梦 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:22

    read() basically is trying to read the whole file and save it into a single string to be used later while readlines() is also trying to read the whole file but it will do a split("\n") and store the strings of lines into a list. Hence, these two methods are not preferred if the file size is excessively big.

    readline() and for loop (i.e.for line in file:) will read one line at a time and store it into a string. I guess they will use the same time to finish the job if memory allows. However these two are preferred if the file size is huge.

提交回复
热议问题