Mixing files and loops
You get the ValueError because your code probably has for line in original:
in addition to original.readline()
. An easy solution which fixes the problem without making your program slower or consume more memory is changing
for line in original: ...
to
while True: line = original.readline() if not line: break ...
Assuming you need only one line, this could be of help
import itertoolsdef getline(fobj, line_no): "Return a (1-based) line from a file object" return itertools.islice(fobj, line_no-1, line_no).next() # 1-based!>>> print getline(open("/etc/passwd", "r"), 4)'adm:x:3:4:adm:/var/adm:/bin/false\n'
You might want to catch StopIteration errors (if the file has less lines).