Python Program for Reading Last N Lines of a File

Files in Python:

Python file handling is a way of saving program output to a file or reading data from a file. File handling is a crucial concept in the programming world. File management is used in almost every form of project. Assume you are constructing an inventory management system. You have data in the inventory management system related to sales and purchases, thus you must save that data somewhere. Using Python’s file management, you can save that data to a file. You must be given data in the form of a comma-separated file or a Microsoft Excel file if you wish to conduct data analysis. Using file handling, you can read data from a file and write output back into it.

Give the N value and file the task is to read the last n lines of the file in Python.

Program for Reading Last N Lines of a File in Python

Method #1: Using For loop (Static Input)

The concept behind this technique is to utilize a negative iterator with the readlines() function to read all of the lines requested by the user from the end of the file.

Approach:

  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Give the n value as static input and store it in a variable.
  • Open the file in read-only mode. In this case, we’re simply reading the contents of the file.
  • Get all the lines of the file using the readlines() function and store it in a variable.
  • Iterate in the above lines list using the for loop to get the last n lines of a file using the negative indexing.
  • Print the last n lines of a given file.
  • The Exit of Program.

Below is the implementation:

# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Give the n value static input and store it in a variable.
gvn_n_val = 2
# Open the file in read-only mode. In this case, we're simply reading the contents of the file.
with open(givenFilename, 'r') as givenfilecontent: 
    # Get the lines of the file using the readlines() function
    lines_lst= givenfilecontent.readlines()
    print("The last",gvn_n_val,"lines of a given file are:")
    # Iterate in the above lines list using the for loop to get the last
    # n lines of a file using the negative indexing.
    for fline in (lines_lst[-gvn_n_val:]):
        # Print the last n lines of a given file.
        print(fline, end ='')
 
 

Output:

The last 2 lines of a given file are: 
BTech Geeks have listed a wide collection 
of Python Programming Examples.

Method #2: Using For loop (User Input)

Approach:

  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Give the n value as user input using the int(input()) function and store it in a variable.
  • Open the file in read-only mode. In this case, we’re simply reading the contents of the file.
  • Get all the lines of the file using the readlines() function and store it in a variable.
  • Iterate in the above lines list using the for loop to get the last n lines of a file using the negative indexing.
  • Print the last n lines of a given file.
  • The Exit of Program.

Below is the implementation:

# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Give the n value user input using the int(input()) function and store it in a variable.
gvn_n_val = int(input("Enter some random number = "))
# Open the file in read-only mode. In this case, we're simply reading the contents of the file.
with open(givenFilename, 'r') as givenfilecontent: 
    # Get all the lines of the file using the readlines() function
    lines_lst= givenfilecontent.readlines()
    print("The last",gvn_n_val,"lines of a given file are:")
    # Iterate in the above lines list using the for loop to get the last
    # n lines of a file using the negative indexing.
    for fline in (lines_lst[-gvn_n_val:]):
        # Print the last n lines of a given file.
        print(fline, end ='')
 
 

Output:

Enter some random number = 3 
The last 3 lines of a given file are: 
The best way to learn the language is by practicing. 
BTech Geeks have listed a wide collection 
of Python Programming Examples.

File Content:

hello this is btechgeeks
welcome to btechgeeks
Good morning this is btechgeeks 
By now you might be aware that Python is a Popular Programming Language 
used right from web developers to data scientists. Wondering what exactly Python looks like and how it works? 
The best way to learn the language is by practicing. 
BTech Geeks have listed a wide collection
of Python Programming Examples.

Google Colab Images:

Files and Code: