1

If I want to see only data between line number 5 to what comes before last 5 rows in a file. While I was reading that particular file.

Code I have used as of now :

f = open("/home/auto/user/ip_file.txt")
lines = f.readlines()[5:] # this will start from line 5 but how to set end
for line in lines:
        print("print line ", line )

Please suggest me I am newbie for python. Any suggestions are most welcome too.

Indrajeet Gour
  • 4,020
  • 5
  • 43
  • 70

1 Answers1

3

You could use a neat feature of slicing, you can count from the end with negative slice index, (see also this question):

lines = f.readlines()[5:-5]

just make sure there are more than 10 lines:

all_lines = f.readlines()
lines = [] if len(all_lines) <= 10 else all_lines[5:-5]

(this is called a ternary operator)

Community
  • 1
  • 1
DomTomCat
  • 8,189
  • 1
  • 49
  • 64