Read only the first line of a file?


Question

How would you get only the first line of a file as a string with Python?

1
172
10/30/2016 2:49:51 AM

Use the .readline() method (Python 2 docs, Python 3 docs):

with open('myfile.txt') as f:
    first_line = f.readline()

Some notes:

  1. 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.
  2. The with statement automatically closes the file again when the block ends.
  3. The with statement only works in Python 2.5 and up, and in Python 2.5 you need to use from __future__ import with_statement
  4. In Python 3 you should specify the file encoding for the file you open. Read more...
295
2/27/2018 2:33:09 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon