使用仅生成器一次从文本文件中读取和打印N行

时间:2017-06-20 21:10:21

标签: generator python-3.6

Python 3.6.0

textfile = "f:\\mark\\python\\Alice_in_Wonderland.txt"

N = 60


def read_in_lines(file, n):
    with open(file) as fh:
        for i in range(n):
            nlines = fh.readline()
            if nlines:
                yield nlines
            else:
                break

for lines in read_in_lines(textfile, x):
    print(lines)

文件位于:https://www.gutenberg.org/files/11/11.txt

我的目标是一次读取这个文件N行,然后打印行, 然后阅读接下来的N行,打印,重复......

如果N = 3,输出应如下所示:

line1
line2
line3

line4
line5
line6

line7
line8
line9

line10  <-- assumes this is the last line in the file

以上打印图案应适用于&#39; N&#39;

的任何值

如果&#39; N&#39; = 4:

line1
line2
line3
line4

line5
line6
line7
line8

等。你明白了。

没有列表。没有内置函数(islice等)。

我只需要使用发电机。 每次迭代必须包含一个包含最多的字符串 由&#39; N&#39;

指定的行数

两个问题:

1)上面的代码返回&#39; N&#39;线,然后停止。我想我需要把整个 循环中的东西,但我不确定如何继续。 (新手...)

2)该文件包含大量空白行。每次我尝试使用strip() 或者它的任何变体,无论我做多大,N&#39; N&#39; N&#39; N&#39; N&#39;它只打印一行。

nlines = fh.readline()。strip&lt; - 添加.strip() 当N = 6000时,我得到:

Project Gutenberg's Alice's Adventures in Wonderland, by Lewis Carroll

Process finished with exit code 0

如果我摆脱.strip(),我会得到所有的行,但不是我想要的格式。

我在Win 10机器上。在Notepad ++中,文件符号的所有末尾都是CRLF。

1 个答案:

答案 0 :(得分:1)

解决:

textfile = "f:\\mark\\python\\test.txt"


def read_n(file, x):
    with open(file, mode='r') as fh:
        while True:
            data = ''.join(fh.readline() for _ in range(x))

            if not data:
                break

            yield data
            print()


for nlines in read_n(textfile, 5):
    print(nlines.rstrip())

输出:

abc
123
def
456
ghi

789
jkl
abc
123
def

456
ghi
789
jkl
abc

123
def
456
ghi
789

jkl
abc
123
def
456

ghi
789
jkl