Search code examples
pythonfilefile-read

Want to skip last and first 5 lines while reading file in python


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.


Solution

  • 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)