简体   繁体   中英

Python skip operation on first line of file

I have a csv file which looks like following:

CCC;reserved;reserved;pIndex;wedgeWT;NA;NA;NA;NA;NA;xOffset;yOffset;zOffset
0.10089,0,0,1,0,0,0,0,0,0,-1.8,-0.7,1999998
0.1124,0,0,3,0,0,0,0,0,0,-1.2,1.8,-3.9

I am using the fileinput method to do some operation in the file, but I want to skip the operation on the first (header) line, though still keeping it there. I have tried using next(f) and f.isfirstline() , but they delete the header line. I want to keep the header line intact, though not doing any operation on it.

with fileinput.input(inplace=True) as f:
    #skip line
    for line in f:
    .
    .

You can use enumerate to easily keep track of the line numbers:

for linenum, line in enumerate(f):
    if linenum == 0:
        # 'line' is the header line
        continue

    # 'line' is a data line
    # ...

You can use iter and skip it with next :

with fileinput.input(inplace=True) as f:
    iterF = iter(f)
    print next(iterF)#skipping computation but printing data
    for line in iterF:
        #...

This way you will just get the overhead of creating the iterator once, but will not create the indexes nor compute an if in each iteration loop as in @JonathonReinhart solution (wich is also valid).

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