Python Program Equal to Linux [tail -1] Command

Here’s a sample python program, which works as the Linux tail -1 command. Python’s text file data you can read and update using file commands. Here’s a magical python program for your reference.

Table of contents

  1. Python reading a file
    1. Python program reads all the records
  2. Python program equal to Linux tail -1

Python reading a file

With the readline() or readlines() method, you can read file contents in python. After you set read mode, you need the for loop to read records. Begin and end of the positions, if you specify, you can read. It is not surprising.

The surprising point is, if you decide to read only the last record, how to get it is a surprise for you.

Python program reads all the records

The Below code sets the python file to read mode. And it reads all the rows.

# Open the file and read in all of the lines

with open('file1.txt', 'r') as f:
    lines = f.readlines()
print(lines)

The output displays all three records. This’s just normal.

['1111111111111\n', '222222222222\n', '3333333333']
** Process exited - Return Code: 0 **
Press Enter to exit terminal

Python program equal to Linux tail -1

When you give the tail -1 [linuxfoundation.org] command, it shows the last record. Similarly, the python program works. We will see how.

The input file file1.txt has three records. The data of the input file is as below.

#file1.txt
1111111111111
222222222222
3333333333

So, when you use the below logic, you will get the last record. That is 3333333333.

# Open the file and read in all of the lines

with open('file1.txt', 'r') as f:
    lines = f.readlines()

 # Now, get the ones they want to see
    for i in lines[len(lines)-1:]:
 # Strip off trailing newline
        print(i[0:len(i)-1])

The output shows the last record.

333333333

** Process exited - Return Code: 0 **
Press Enter to exit terminal

Read

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.