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

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

    If file is huge, read() is definitevely bad idea, as it loads (without size parameter), whole file into memory.

    Readline reads only one line at time, so I would say that is better choice for huge files.

    And just iterating over file object should be as effective as using readline.

    See http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects for more info

    0 讨论(0)
  • 2020-11-30 06:48

    Neither. Both of them will read the content into memory. In case of big files, iterating over the file object only loads one line of your file at a time and is perhaps a good way to deal with the contents of a huge file.

    0 讨论(0)
提交回复
热议问题