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

标签 python file

首先,我是 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 
...

我有以下代码:

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

在这种情况下它只打印

"This is line four".

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

最佳答案

open的返回值是一个迭代器(因此是可迭代的),因此您可以将它传递给 itertools.islice :

islice(iterable, start, stop[, step]) --> islice object
Return an iterator whose next() method returns selected values from an iterable. [...]

演示:

data.txt:

line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
line11
line12
line13

代码:

from itertools import islice

with open('data.txt') as f:
    for line in islice(f, 3, None, 3):
        print line,  # Python3: print(line, end='')

产生:

line4
line7
line10
line13

关于python - 如何遍历文件中的每第 n 行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36487709/

相关文章:

c++ - istringstream 不在变量中存储任何内容

java - 从字节数组中提取 WAV 文件

python - VSCode 终端不显示所有行

python - 相当于numpy的cv::MatIterator

video - 我应该在jar文件的manifest.mf文件中给出哪个主类,该jar文件中有一个没有主类的applet?

c - Linux C 打开()失败

python - 使用 Telethon 发送消息(Python 的 Telegram API 客户端)

python - SWIG:将 std::map 访问器与 shared_ptr 一起使用?

python - 在对列表字典进行排序时解决平局

python文件操作