Hurry! Try our new Interactive Courses for FREE. 🥳   🚀
  Signup/Sign In

How to Read only the First Line of the File?

In this article, we will learn how one can read the first line only from a file in Python. We will use some built-in functions, some simple approaches, and some custom codes as well to better understand the topic.

Python handles various file operations. In the case of reading files, if the user wants to read only the first line or maybe a header, Python provides readline() function for it. Let us discuss three different methods to read the first line of the file. We will read the first line of the given sample.txt file.

Sample Text File

It is an exciting time to be a book reviewer. 
Once confined to print newspapers and journals, 
reviews now dot many corridors of the Internet
forever helping others discover their next great read.

Example: Read the First Line using next()

We use the sample.txt file to read the first line. We open the file in read mode and uses next() to store the first line in a variable. The below code uses strip() function to remove extra newline characters. You can remove it according to your need.

with open('sample.txt', 'r') as f:
    first_line = next(f).strip()
print(first_line)


It is an exciting time to be a book reviewer.

Example: Read the First Line using readlines()

We use the sample.txt file to read the contents. This method uses readlines() to store the first line. readlines() uses the slicing technique. As you can see in the below example, firstline[0].strip(), it denotes the stripping of newlines spaces from index 0. This is a much more powerful solution as it generalizes to any line. The drawback of this method is that it works fine for small files but can create problems for large files.

with open('sample.txt', 'r') as f:
    first_line = f.readlines()
print(first_line[0].strip())


It is an exciting time to be a book reviewer.

Example: Read the First Line using readline()

We use the sample.txt file to read the contents. This is an efficient and pythonic way of solving the problem. This even works for in-memory uploaded files while iterating over file objects. This simply uses readline() to print the first line.

with open('sample.txt', 'r') as f:
    first_line = f.readline().strip()
print(first_line)


It is an exciting time to be a book reviewer.

Note: Observe your output when you run the above code snippets without strip() function. You will notice an empty line along with the first line.

Conclusion

In this article, we learned to read the first line of the file by using several built-in functions such as next(), readlines(), readline() and different examples to read the first line from the given file.