简体   繁体   中英

Skip first row in a file

I'm trying to open 2 files, read the contents of both files, and export the rows of both files to an output file.

The issue I'm having is that the 2nd file that I'm reading in has the same headers in it's first row as the 1st, so I'm trying to skip writing the 1st row of the 2nd file to my new outputFile , but the code written below doesn't execute that.

I know my code says if row[1]=='Full Name' and not column[1] , but if I skip writting row[1] to the outputFile , it skips the first column and not the first row, so I figured I'd use that first column in my if statement. The first column's header in my input data is Full Name , so that's why I used that particular if statement.

I didn't include incoming data because I didn't think it was necesary to answer this question, but if you feel it would be helpful, I'm more than glad to post it up here.

If anyone can help me skip writing the first row of the second incoming into my outputFile it would be greatly appreciated.

import csv, sys

firstFile = open(sys.argv[1],'rU')# U to parse
reader1 = csv.reader(firstFile, delimiter=',')
outputFile = open((sys.argv[3]), 'w')
for row in reader1:
     row=(str(row))
     row=row.replace("'", "")
     row=row.replace("[", "")
     row=row.replace("]", "")
     outputFile.write(row)
     outputFile.write('\n')

 secondFile = open(sys.argv[2],'rU')
 reader2 = csv.reader(secondFile, delimiter=',')
 for row in reader2:
     row=(str(row))
     row=row.replace("'", "")
     row=row.replace("[", "")
     row=row.replace("]", "")
     if row[1]=='Full Name':
         next(reader2)
    else:
         outputFile.write(row)
         outputFile.write('\n')

You can use the next function:

secondFile = open(sys.argv[2],'rU')

# skip first line
next(secondFile)

# csv parser does not see the first line of the file
reader2 = csv.reader(secondFile, delimiter=',')

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