如何在python中打印行并跳过行?

问题描述 投票:-1回答:2

我想打印一行并在​​python中跳过一行

示例我有这个文本文件

line1
line2
line3
line4
line5

我希望结果像这样

line1
line3
line5
python python-3.x dictionary count line
2个回答
0
投票
with open(<YOURFILE>) as myfile:
    line = myfile.readline()
    while line is not None:
        do stuff with line here
        line = myfile.readline()
        line= myfile.readline()

0
投票

您未指定要删除的行,但:

f = open(<filename here>).read()
lines = f.split("\n")
#drop line 3
lines_for_print = lines[0:2]+lines[4:]
#drop by condition:
lines_for print = [line for line in lines if <condition here> ]

希望这会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.