Python Program to Read First n Lines of a File


In this article, we will show you how to read and print the first N lines of a text file for the given N value using python.

Assume we have taken a text file with the name ExampleTextFile.txt consisting of some random text. We will return the first N lines of a text file for the given N value.

ExampleTextFile.txt

Good Morning Tutorials Point
This is Tutorials Point sample File
Consisting of Specific
abbreviated
source codes in Python Seaborn Scala
Imagination
Summary and Explanation
Welcome user
Learn with a joy

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the path of the text file.

  • Enter the N value static/dynamic for printing the first N lines of a file.

  • Use the open() function (opens a file and returns a file object as a result) to open the text file in read-only mode by passing the file name, and mode as arguments to it (Here “r” represents read-only mode).

with open(inputFile, 'r') as filedata:
  • Using the readlines() function (returns a list with each line in the file represented as a list item. To limit the number of lines returned, use the hint argument. No more lines are returned if the total amount of bytes returned exceeds the specified number) to obtain the list of lines of a given input text file.

file.readlines(hint)
  • Traverse in the list of lines to retrieve the first N lines of a text file using slicing (Using the slice syntax, you can return a range of characters. To return a part of the string, specify the start and end indexes, separated by a colon). Here linesList[:N] indicates all the lines till N (excluding the last Nth line since the index starts from 0) from the starting.

for textline in (linesList[:N]):
  • Print the first N lines of the file line by line.

  • Close the input file with the close() function (used to close an opened file).

Example

The following program prints the first N lines of a text file for the given N value −

# input text file inputFile = "ExampleTextFile.txt" # Enter N value N = int(input("Enter N value: ")) # Opening the given file in read-only mode with open(inputFile, 'r') as filedata: # Read the file lines using readlines() linesList= filedata.readlines() print("The following are the first",N,"lines of a text file:") # Traverse in the list of lines to retrieve the first N lines of a file for textline in (linesList[:N]): # Printing the first N lines of the file line by line. print(textline, end ='') # Closing the input file filedata.close()

Output

On executing, the above program will generate the following output −

Enter N value: 4 The following are the first 4 lines of a text file:
Good Morning Tutorials Point
This is Tutorials Point sample File
Consisting of Specific
abbreviated

We took the value of N from the user (dynamic Input) and then gave our program a text file containing some random content and then opened it in reading mode. The readlines() function was then used to retrieve a list of all the lines in the file. We traversed the first N lines of the file using the for loop and slicing and printed them.

Conclusion

So, from this article, we learned how to open a file and read lines from it, which can be used to execute operations such as finding the number of words in a line, the length of a line, and so on, and we also learned slicing to access the elements from the start or end in a simple way.

Updated on: 18-Aug-2022

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements