2013-11-15 53 views
0

我無法解決如何打開文件以讀取第7行的文字&並忽略該行的所有內容。如何從某一行開始閱讀?

# Title # 
<br /> 
2013-11-15 
<br /> 
5 
6 
Random text 

我沒試過這裏所描述的方法: python - Read file from and to specific lines of text

,但它搜索特定的匹配,包括上面那行文字。我需要相反的東西,包括從第7行開始的所有內容。

+3

剛讀6線,不跟他們做什麼? –

+0

我想讀取從第7行開始的所有內容並忽略所有前面的行[1-6] – HexSFd

+0

對。因此,打開文件,讀取前六行並將它們扔掉,然後開始處理其他事情。 –

回答

1

這將忽略前6行,然後從第7行打印所有行。

with open(file.txt, 'r') as f: 
    for i, line in enumerate(f.readlines(), 0): 
      if i >= 6: 
       print line 

或@Paco建議:

with open(file.txt, 'r') as f: 
    for line in f.readlines()[6:]: 
      print line 
+0

你不應該讀所有行到'readlines'列表。 – iruvar

+0

@Paco我喜歡這樣,我更新了我的答案。謝謝。 – jramirez

+0

提示:[itertools.islice](http://docs.python.org/2/library/itertools.html#itertools.islice) – iruvar

2

你可以這樣做:

首先創建一個演示文件:

# create a test file of 'Line X of Y' type 
with open('/tmp/lines.txt', 'w') as fout:  
    start,stop=1,11 
    for i in range(start,stop): 
     fout.write('Line {} of {}\n'.format(i, stop-start)) 

現在與文件中的行,由工作-line:

with open('/tmp/lines.txt') as fin: 
    # skip first N lines: 
    N=7 
    garbage=[next(fin) for i in range(N)] 
    for line in fin: 
     # do what you are going to do... 

您還可以使用itertools.islice

import itertools   
with open('/tmp/lines.txt') as fin: 
    for line in itertools.islice(fin,7,None): 
     # there you go with the rest of the file... 
+0

謝謝dawg。 – HexSFd