2016-11-16 130 views
1

我对python非常陌生。我试图提取特定的行,跳过标题行,这些标题行在文本文件中以定期间隔重复,并将它们写入另一个文件中。我已经能够用下面的代码做到这一点,但这非常缓慢。尽管循环文件来提取行

import random 
import sys 
import os 

with open('test.txt', encoding ='latin1') as rf: 
    with open('test1.txt', 'w') as wf: 
     for x, line in enumerate(rf): #reads the line number 
      #nskip = 3 #number of headers to skip 
      #nloop = 5 #number of loops in the file 
      ndata = 7 #number of lines in each loop 
      data = 4 #number of lines to be extracted 
      x+=1 
      #print(x,line) 

      for i in range(1,ndata+1): 
       for j in range((ndata*i - data)+1, ndata*i+1): 
        if x == j: 
         #print(line) 
         wf.write(line) 

例如,从这段代码中,我可以得到Line5,Line6,Line7,Line12,Line13,Line14,Line19,Line20,Line21(如果你认为测试文件中有Line1,Line2,Line3等每行) 。但问题是我真正的文件更大,需要大量的时间和记忆。这样做肯定会有一种更快捷的pythonic方式。

另外,我希望能够在每个循环中添加循环数,即第1个循环将在所有行中获得1(每行中的某处可能是Line5 1,Line6 1,Line7 1,Line12 2,Line13 2,Line14 2,Line19 3等)。尽管我想要做的比这个有些复杂。但是这应该通过我的方式铺平道路。 谢谢。

回答

2

由于标题和记录的大小固定,因此跳过数字标题行并重复写入记录行数直到达到文件末尾。

n_header_lines = 25 
n_record_lines = 100 
page_num = 0 

with open('test.txt', encoding ='latin1') as rf, with open('test1.txt', 'w') as wf: 
    try: 
     while True: 
      page_num += 1 
      for _ in range(n_header_lines): 
       next(rf) 
      for line_num in range(1, n_record_lines + 1): 
       prefix = 'Line {:3d} {:3d} '.format(line_num, page_num) 
       wf.write(prefix + next(rf))) 
    except StopIteration: 
     pass 
+0

试过这与n_header_lines = 4和n_record_lines = 3. 7行中的每个循环中的测试文件:该出放是线5,7,9,15,17,19,25,27,29等等......我希望是5,6,7,12,13,14,19,20,21等。所以代码没有那么有用。还有什么建议?感谢这篇文章。 – Luck4u

+0

@ Luck4u:这个每隔一行的跳过都会表明你在调用'next(rf)'之外的'rf'上迭代。确保你没有任何代码,比如'for line in rf:'。还要记住每次调用'next(rf)'都会占用一行。如果你在for循环中这样做了两次,它将以预期的两倍消耗。我想说的是,这个概念是合理的,你的实现是缺乏的。如果您想让我查看它,请将它添加到您的问题中。 –

+0

刚刚编辑的问题。希望它现在更有意义。谢谢! – Luck4u