Read only the first line of a file?
with open('myfile.txt') as f: first_line = f.readline()
- As noted in the docs, unless it is the only line in the file, the string returned from
f.readline()will contain a trailing newline. You may wish to use
f.readline().strip()instead to remove the newline.
withstatement automatically closes the file again when the block ends.
withstatement only works in Python 2.5 and up, and in Python 2.5 you need to use
from __future__ import with_statement
- In Python 3 you should specify the file encoding for the file you open. Read more...