简体   繁体   中英

How to make python disregard first couple of lines of a text file

I was wondering if it was possible to make python disregard the first 4 lines of my text file. Like if I had a text file which looked like this:

aaa
aaa
aaa
aaa
123412
1232134

Can I make it so python starts working from the numbers?

Use next and a loop:

with open("/path/to/myfile.txt") as myfile:
    for _ in range(4):  # Use xrange here if you are on Python 2.x
        next(myfile)
    for line in myfile:
        print(line)  # Just to demonstrate

Because file objects are iterators in Python, a line will be skipped each time you do next(myfile) .

This should do the trick

f = open('file.txt')
for index,line in enumerate(f):
    if index>3:
      print(line)

assuming you know the number of lines to discard, you can use this method:

    for i, line in enumerate(open('myfile')):
        if i < number_of_lines_to_discard:
            continue
        # do your stuff here

or if you just want to disregard non numeric lines:

    for line in open('myfile'):
        if not re.match('^[0-9]+$\n', line):
             continue
        # do your stuff here

A more robust solution, not relying on the exact number of lines:

with open(filename) as f:
    for line in f:
        try:
            line = int(line)
        except ValueError:
            continue
        # process line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM