Read the bottom n lines of a file in Python

Using Operating System Commands in Python

Use the Linux/Mac tail command to provide the data:

line = subprocess.check_output(['tail', '-1', somefile.txt])
Code language: SQL (Structured Query Language) (sql)

Creating a Python Only Script

Read the whole file into memory and only print out the last line/s:

with open('somefile.txt', 'r') as f: lines = f.read().splitlines() last_line = lines[-1] print(last_line)
Code language: SQL (Structured Query Language) (sql)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments