2017-06-20 52 views
0

的Python 3.6.0阅读并使用一台发电机从一次一个文本文件中N行只打印

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)上面的代码返回 'N' 线,然后停止。我假设我需要把整个 事情放在一个循环中,但我不确定如何继续。 (新手...)

2)该文件包含很多空白行。每次尝试使用strip() 或它的任何变体时,无论我使'N'多大,它只打印一行。 。

nlines = fh.readline()剥离< - 将在.strip() 具有N = 6000 I得到:

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

Process finished with exit code 0 

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

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

+0

我拉近了许多。我可以打印第一个'N'行然后是一个空格,但是我似乎无法弄清楚如何继续下一个'N'行等,直到文件结束。 – MarkS

+0

文本文件= “F:\\标记\\蟒\\ Reuven_Lerner \\ test.txt的” X = 3个 DEF read_in_lines(文件,N): 与打开(文件)作为FH: 对于i在范围(n): nlines = fh。的ReadLine() 如果不是nlines: 断裂 收率nlines 打印( “空间”) 用于read_in_lines线(文本文件中,x): 打印(lines.rstrip()) – MarkS

回答

0

解决:

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