Skip to content Skip to sidebar Skip to footer

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

Solution 1:

This should do the trick

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

Solution 2:

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

Solution 3:

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

Post a Comment for "How To Make Python Disregard First Couple Of Lines Of A Text File"