简体   繁体   English

想要在python中读取文件时跳过最后5行和前5行

[英]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. 如果我只想查看第5行到文件最后5行之间的数据。 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. 请建议我我是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 ) (这被称为三元运算符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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