Python - How To Read First Line of a File in Python

ID : 426

viewed : 136

Tags : PythonPython File

vote vote

98

In Python, we have built-in functions that can handle different file operations. A Text file contains a sequence of strings in which every line terminated using a newline character \n.

In this tutorial, we will learn how to read the first line of a text file in Python.

We can use the open() function to create a file object by passing the file path to the function and open a file in a specific mode, read mode by default.

Use the read() Function to Read the First Line of a File in Python

The read() function is used to read the data from a file. To extract the first line from the file, we can simply use the split() function to get a list of all the lines separated based on the newline character, and extract the first line from this list. For example:

with open("sample.txt") as f:     lines = f.read() ##Assume the sample file has 3 lines     first = lines.split('\n', 1)[0]  print(first) 

Output:

Sample File Line 1 

Use the readline() Function to Read the First Line of File in Python

Another method to read the first line of a file is using the readline() function that reads one line from the stream.

with open("sample.txt") as f:     firstline = f.readline().rstrip()  print(firstline) 

Output:

Sample File Line 1 

Notice that we use the rstrip() function to remove the newline character at the end of the line because readline() returns the line with a trailing newline.

Use the readlines() Function to Read the First Line of a File in Python

We can also use the readlines() function, which reads all the lines from the file and returns a list of each line as the list item, and then extract the first line from the returned list. For example:

with open("sample.txt") as f:     firstline = f.readlines()[0].rstrip()      print(firstline) 

Output:

Sample File Line 1 

Use the next() Function to Read the First Line of a File in Python

An unconventional method of achieving the same is by using the next() function. It returns the next item in an iterator. So if we pass the file object to the next() function, it returns the first line of the file. For example:

with open("sample.txt") as f:     firstline = next(f)      print(firstline) 

Output:

Sample File Line 1 

  • Related HOW TO?