How to Read the First Line of a File in Python

5/5 - (12 votes)

Problem Formulation and Solution Overview

This article will show you how to read and display the first line of a file in Python.

For this article, we will work with a flat-text file containing five (5) possible things to do during your lifetime. This file is saved to bucket_list.txt and placed into the current working directory.

File Contents

1Bring a Fishing Pole to an Aquarium.
2Call Someone To Tell Them You Can’t Talk Right Now.
3Send a Hogwarts acceptance letter to a random address and see if they respond.
4Switch Your Friends Phone To A Foreign Language.
5Create a Piece of Art and Put it on Etsy for $1,000,000.

πŸ’¬ Question: How would we write code to retrieve the first line of a file?

We can accomplish this task by one of the following options:


Method 1: Use readline() and strip()

This method uses Python’s built-in readline() function. This function reads a single line from the file.

with open('bucket_list.txt', 'r') as fp:
    first_item = fp.readline().strip()
print(first_item)

The first line in the above code opens the bucket_list.txt file in read (r) mode and creates a File Object (fp) of the same. This object allows us access to and manipulation of files. If output to the terminal, an object similar to the one below would display.

<_io.TextIOWrapper name='bucket_list.txt' mode='r' encoding='cp1252'>

The following line references fp and appends readline() to read in the first line of said file. Next, strip() is applied to remove extraneous spaces and newline characters from the line. The results save to first_line and output to the terminal.

1 Bring a Fishing Pole to an Aquarium.
Python open() Function -- An 80/20 Guide by Example

Method 2: Use readlines() and slicing

This method uses Python’s built-in function readlines(). This function reads the contents of a file. Slicing is used to access the first line.

with open('bucket_list.txt') as fp:
    all_lines = fp.readlines()
print(all_lines[0].strip())

The first line in the above code opens the bucket_list.txt file in read (r) mode and creates a File Object (fp) of the same. This object allows us access to and manipulation of files. If output to the terminal, an object similar to the one below would display.

<_io.TextIOWrapper name='bucket_list.txt' mode='r' encoding='cp1252'>

The following line references fp and appends readlines() to read the entire file contents. The results save to all_lines as a List. If output to the terminal, the following would display.

['1 Bring a Fishing Pole to an Aquarium.\n', "2 Call Someone To Tell Them You Can't Talk Right Now.\n", '3 Send a Hogwarts acceptance letter to a random address and see if they respond.\n', "4 Switch Your Friend's Phone to a Foreign Language.\n", '5 Create a Piece of Art and Put it on Etsy for $1,000,000.']

The last line extracts the first line from all_lines using slicing. Then strip() is applied to remove extraneous spaces and newline characters. The results are output to the terminal.

1 Bring a Fishing Pole to an Aquarium.
The Ultimate Guide to Slicing in Python

Method 3: Use next()

An elegant and efficient way to read the first line of a file! This method uses Python’s built-in next() function!

first_line = next(open('bucket_list.txt'))
print(first_line.strip())

The code in the above line, calls the next() function and passes it one argument: an iterator. In this case, the filename, bucket_list.txt.

This function returns the next value from the iterator: the first line of the file. The results save to first_line.

Next, strip() is applied to remove extraneous spaces and newline characters. The results are output to the terminal.

1 Bring a Fishing Pole to an Aquarium.
Python next() -- A Simple Guide By Example

🌟A Finxter Favorite!


Method 4: Use read(), split() and slicing

This method uses Python’s built-in function read() to read a file’s contents, in conjunction with split() and slicing to extract the first line.

with open('bucket_list.txt', "r") as fp:
    all_lines = fp.read()
    first_line = all_lines.split('\n', 1)[0]
print(first_line)

The first line in the above code opens the bucket_list.txt file in read (r) mode and creates a File Object (fp) of the same. This object allows us access to and manipulation of files. If output to the terminal, an object similar to the one below would display.

<_io.TextIOWrapper name='bucket_list.txt' mode='r' encoding='cp1252'>

The following line references fp and appends read() to read the entire file contents. The results save to all_lines as a List. If output to the terminal, the following would display.

['1 Bring a Fishing Pole to an Aquarium.\n', "2 Call Someone To Tell Them You Can't Talk Right Now.\n", '3 Send a Hogwarts acceptance letter to a random address and see if they respond.\n', "4 Switch Your Friend's Phone to a Foreign Language.\n", '5 Create a Piece of Art and Put it on Etsy for $1,000,000.']

The next line splits the above List on the newline character (\n), retrieves the first line in the file using slicing. The results save to first_line and are output to the terminal.

1 Bring a Fishing Pole to an Aquarium.
Python String Methods [Ultimate Guide]

Method 5: Use getline()

This method uses the getline() function to read the first line of a file.

import linecache as lc
  
first_line = lc.getline('bucket_list.txt', 1)
print(first_line.strip())

The first line in the above code imports the linecache library. This library is built-in to Python and does not require installation.

The following line uses the getline() function and passes it two (2) arguments: a filename, and the line number to read. The results save to first_line.

Next, strip() is applied to remove extraneous spaces and newline characters. The results are output to the terminal.

1 Bring a Fishing Pole to an Aquarium.

Summary

This article has provided five (5) ways to read the first line of a file to select the best fit for your coding requirements.

Good Luck & Happy Coding!


Programmer Humor – Blockchain

“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.” source xkcd