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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
For a text file just iterating over it with a
forloop is almost always the way to go. Never mind about speed, it is the cleanest.In some versions of python
readline()really does just read a single line while theforloop reads large chunks and splits them up into lines so it may be faster. I think that more recent versions of Python use buffering also forreadline()so the performance difference will be minuscule (foris probably still microscopically faster because it avoids a method call). However choosing one over the other for performance reasons is probably premature optimisation.Edit to add: I just checked back through some Python release notes. Python 2.5 said:
Python 2.6 introduced TextIOBase which supports both iterating and
readline()simultaneously.Python 2.7 fixed interleaving
read()andreadline().