简体   繁体   中英

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.

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM