0

I'm unable to solve how can I open file for reading & writing from line 7 and to ignore everything above that line.

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

I did tried the method described here: python - Read file from and to specific lines of text

but it searches for specific match and includes the text above that line. I need the reverse, to include everything starting from line 7.

Community
  • 1
  • 1
HexSFd
  • 217
  • 4
  • 9
  • 3
    just read 6 lines and don't do anything with them? – Mark Reed Nov 15 '13 at 18:13
  • I want to read everything starting from line 7 and to ignore all the previous lines [1-6] – HexSFd Nov 15 '13 at 18:14
  • Right. So open the file, read the first six lines and throw them away, and then start whatever you were going to do with the rest. – Mark Reed Nov 15 '13 at 18:22
  • I think you misunderstood Mark Reed. How do you mean "ignore"? I guess you want to do something with line 7 after reading it. So you can only read and then ignore lines 1-6, and finally read and do something with line 7. – leeladam Nov 15 '13 at 18:22

2 Answers2

2

This will ignore the first 6 lines then print all the lines from the 7th on.

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

or as @Paco suggested:

with open( file.txt, 'r') as f:
     for line in f.readlines()[6:]:
          print line
jramirez
  • 8,537
  • 7
  • 33
  • 46
2

You can do this:

First create a demo file:

# 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))

Now work with the file line-by-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...

You can also use 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...  
dawg
  • 98,345
  • 23
  • 131
  • 206