Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip 2 lines in a file with Python?

I have a series of files and I want to extract a specific number from each of them. In each of the files I have this line:

name, registration num

and exactly two lines after that there is the registration number. I would like to extract this number from each file. and put it as a value of a dictionary.Anyone have any idea how it is possible ?

my current code that does not actually work is like below:

matches=[]
for root, dirnames, filenames in os.walk('D:/Dataset2'):  
    for filename in fnmatch.filter(filenames, '*.txt'):   
        matches.append([root, filename])

filenames_list={}       
for root,filename in matches:
    filename_key = (os.path.join(filename).strip()).split('.',1)[0]

    fullfilename = os.path.join(root, filename)
    f= open(fullfilename, 'r')
    for line in f:
        if "<name, registration num'" in line:
            key=filename_key
            line+=2
            val=line
like image 943
UserYmY Avatar asked Dec 21 '22 06:12

UserYmY


1 Answers

I usually use next() when I want to skip a single line, usually a header for a file.

with open(file_path) as f:
    next(f) # skip 1 line
    next(f) # skip another one.
    for line in f:
        pass # now you can keep reading as if there was no first or second line.

Note: In Python 2.6 or earlier you must use f.next()

like image 92
Inbar Rose Avatar answered Jan 03 '23 21:01

Inbar Rose