想要在 python 中读取文件时跳过最后和前 5 行
Want to skip last and first 5 lines while reading file in python
如果我只想查看文件中第 5 行到最后 5 行之前的数据。当我阅读那个特定文件时。
我目前使用的代码:
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 )
请建议我,我是 python 的新手。
也欢迎任何建议。
您可以使用一个简洁的切片功能,您可以使用负切片索引从末尾开始计数,(see also this question):
lines = f.readlines()[5:-5]
只需确保超过 10 行即可:
all_lines = f.readlines()
lines = [] if len(all_lines) <= 10 else all_lines[5:-5]
(这称为三元运算符)
如果我只想查看文件中第 5 行到最后 5 行之前的数据。当我阅读那个特定文件时。
我目前使用的代码:
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 )
请建议我,我是 python 的新手。 也欢迎任何建议。
您可以使用一个简洁的切片功能,您可以使用负切片索引从末尾开始计数,(see also this question):
lines = f.readlines()[5:-5]
只需确保超过 10 行即可:
all_lines = f.readlines()
lines = [] if len(all_lines) <= 10 else all_lines[5:-5]
(这称为三元运算符)