在 python 中使用 readline() 时是否可以指定要读取的行?当我运行以下代码时,我得到第 1、2、3 行,但我想阅读第 2、6、10 行

def print_a_line(line, f):
    print f.readline(line)

current_file = open("file.txt")

for i in range(1, 12):
    if(i%4==2):
        print_a_line(i, current_file)

最佳答案

with open('file.txt', 'r') as f:
    next(f)
    for line in f:
        print(line.rstrip('\n'))
        for skip in range(3):
            try:
                next(f)
            except StopIteration:
                break

文件:
1
2
3
4
5
6
7
8
9
10

结果:
2
6
10

这适用于脚本或函数,但如果您希望它在交互式 shell 中隐藏跳过的行,则必须将 next(f) 调用保存到临时变量。

关于python - 使用 python 中的 readline() 读取特定行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30721089/

10-12 12:53
查看更多