简体   繁体   中英

Extra row appended when adding columns to CSV file

I am reading in CSV files, removing the header, and appending two columns of data. Everything is working great, aside from an extra row being added at the end. For example, if I have the following input file:

headerA | headerB | headerC
   a    |    b    |    c
   d    |    e    |    f

I want the output file to look like:

   a    |    b    |    c    |    g    |    h
   d    |    e    |    f    |    g    |    h

But it's coming out like:

   a    |    b    |    c    |    g    |    h
   d    |    e    |    f    |    g    |    h
   g    |    h

I cannot for the life of me figure out why this is the case. If anyone has a solution, it would be greatly appreciated. Here's my code:

for fileName in os.listdir(inPath):
    if fileName.endswith('.csv'):
        with open(inPath + fileName, 'rb') as csvin:
            reader = csv.reader(csvin, delimiter=',')
            i = reader.next()
            with open(outPath + 'wrng_' + fileName, 'wb') as csvout:
                writer = csv.writer(csvout, delimiter=',')                         
                for row in reader:
                    j = fileName.split("_")[1].replace(".csv","")
                    row.append(j[2:-7] + '-' + j[4:-5] + '-' + j[:2] + ' ' + j[7:-2] + ':' + j[9:] + ':00')
                    row.append(i[1].split(" ")[2][:-1])
                    writer.writerow(row)

(Summarizing from the comments) It looks like the problem you are having could be caused by an empty row at the end of the file. You can check to see if the row is empty within your for loop.

for row in reader:
    if row:
    ...

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