简体   繁体   English

将列添加到CSV文件时追加了额外的行

[英]Extra row appended when adding columns to CSV file

I am reading in CSV files, removing the header, and appending two columns of data. 我正在读取CSV文件,删除标题,并附加两列数据。 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循环中的行是否为空。

for row in reader:
    if row:
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM