This is related to the In Python, is read() , or readlines() faster? but not exactly the same. I have a small file to read many many times. I found out that reading it with readlines() and joining is faster than reading with read(). I could not find a good explanation for that but it puzzles me.
In [34]: cat test.txt
ATOM 1 N MET A 1 -1.112 -18.674 -30.756 1.00 16.53 N
ATOM 2 CA MET A 1 0.327 -18.325 -30.772 1.00 16.53 C
ATOM 3 C MET A 1 0.513 -16.897 -31.160 1.00 16.53 C
ATOM 4 O MET A 1 -0.063 -15.998 -30.552 1.00 16.53 O
ATOM 5 CB MET A 1 1.083 -19.211 -31.777 1.00 16.53 C
ATOM 6 CG MET A 1 1.101 -20.691 -31.391 1.00 16.53 C
ATOM 7 SD MET A 1 1.989 -21.764 -32.559 1.00 16.53 S
ATOM 8 CE MET A 1 3.635 -21.109 -32.159 1.00 16.53 C
ATOM 9 N LYS A 2 1.333 -16.657 -32.199 1.00146.35 N
ATOM 10 CA LYS A 2 1.595 -15.313 -32.613 1.00146.35 C
In [35]: timeit open("test.txt").read()
10000 loops, best of 3: 58.7 µs per loop
In [36]: timeit "\n".join(open("test.txt").readlines())
10000 loops, best of 3: 56.4 µs per loop
The result is pretty consistent.