In this python file program, we will get the file’s first three and last three lines. Let’s consider we have readcontent.txt file with the below content.
We will read lines of the file with read mode with the help of the below-given steps.
#readcontext.txt
Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
Line5 : This is China.
Steps to solve the program
- Open the file by using open(“file name”,”r”).
- Where file name is the name of the file and r is the reading mode.
- Read the lines in the file using readlines().
- Use a for loop to iterate over lines in the file.
- Using indexing print the first 3 and last 3 lines of the file.
# Open file with read mode
file=open("readcontent.txt","r")
# Read file lines in the list
linesList= file.readlines()
# Print first three lines
for i in (linesList[:3]):
print(i)
# Print last three lines
for i in (linesList[-3:]):
print(i)
Output :
Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line3 : This is Canada.
Line4 : This is Australia.
Line5 : This is China.