仅使用生成器一次从文本文件读取和打印 N 行
Read and print from a text file N lines at a time using a generator only
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
以上打印模式应适用于 'N' 的任何值。
如果'N' = 4:
line1
line2
line3
line4
line5
line6
line7
line8
等你明白了。
没有列表。没有内置函数(islice 等)。
我只需要使用发电机。
每次迭代 必须 包含一个字符串,最多包含
'N'.
指定的行数
两期:
1)上面的代码returns'N'行,然后停止。我想我需要把整个
循环中的事情,但我不确定如何进行。 (新手...)
2) 该文件包含大量空行。每次我尝试使用 strip()
或其任何变体,无论我制作多大 'N' 它只会打印一行。
nlines = fh.readline().strip <-- 添加 .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。
已解决:
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
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
以上打印模式应适用于 'N' 的任何值。
如果'N' = 4:
line1
line2
line3
line4
line5
line6
line7
line8
等你明白了。
没有列表。没有内置函数(islice 等)。
我只需要使用发电机。 每次迭代 必须 包含一个字符串,最多包含 'N'.
指定的行数两期:
1)上面的代码returns'N'行,然后停止。我想我需要把整个 循环中的事情,但我不确定如何进行。 (新手...)
2) 该文件包含大量空行。每次我尝试使用 strip() 或其任何变体,无论我制作多大 'N' 它只会打印一行。
nlines = fh.readline().strip <-- 添加 .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。
已解决:
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