小编bul*_*zer的帖子

如何遍历文件中的每第 n 行?

首先,我是 Python 的新手,确实在寻找答案,但没有运气。到目前为止,我发现只返回一行,就像我下面的代码一样。我尝试了其他解决方案,itertools.islice但总是只得到一条线。

我有一个名为data.txt包含数据行的文件:

This is line one
This is line two 
This is line three 
This is line four 
This is line five 
This is line six 
This is line seven 
...
Run Code Online (Sandbox Code Playgroud)

我有以下代码:

with open('data.txt', 'r') as f:
    for x, line in enumerate(f):
        if x == 3:
            print(line)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,它只打印

“这是第四行”。

我确实明白为什么,但我如何从这里获取它并让它打印第 4、7、10、13 行……?

python file

2
推荐指数
1
解决办法
5426
查看次数

标签 统计

file ×1

python ×1