Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read only the first line of a file?

Tags:

python

file

People also ask

How do I read the first line of a file?

To read the first line of a file in Python, use the file. readline() function. The readline() is a built-in function that returns one line from the file. Open a file using open(filename, mode) as a file with mode “r” and call readline() function on that file object to get the first line of the file.

How do I make the first line of a file read only in Linux?

To look at the first few lines of a file, type head filename, where filename is the name of the file you want to look at, and then press <Enter>. By default, head shows you the first 10 lines of a file. You can change this by typing head -number filename, where number is the number of lines you want to see.


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...

infile = open('filename.txt', 'r')
firstLine = infile.readline()

fline=open("myfile").readline().rstrip()

To go back to the beginning of an open file and then return the first line, do this:

my_file.seek(0)
first_line = my_file.readline()

This should do it:

f = open('myfile.txt')
first = f.readline()