我正在读取csv文件,第一行是标题行。我已经验证了标头已正确传递,但我的输出文件仍然为空。它不会引发任何错误。

def main():
    infile = sys.argv[1]
    outfile = sys.argv[2]
    myreader = csv.DictReader(open(infile, 'rbU'))
    for line in myreader:
        print(line['ADDR_NAME'])
    mywriter = csv.DictWriter(open(outfile, 'wb'),
                              fieldnames=myreader.fieldnames)
    #print(mywriter.fieldnames)
    for row in myreader:
        mywriter.writerow(outfile)

最佳答案

您应该在最后一行中将dict传递给mywriter.writerow,而不是当前正在执行的字符串(文件路径)。请参见writer docs

如果您只是尝试将所有行从myreader复制到mywriter,则还需要重新排列一下:首先打开您的阅读器和编写器,然后合并两个for循环:

def main():
    infile = sys.argv[1]
    outfile = sys.argv[2]
    myreader = csv.DictReader(open(infile, 'rbU'))
    mywriter = csv.DictWriter(open(outfile, 'wb'),
                              fieldnames=myreader.fieldnames)
    for row in myreader:
        print(row['ADDR_NAME'])
        mywriter.writerow(row)


正如克里斯蒂安(Cristian)所提到的,.close是您open的文件也是一个好习惯,但这不应该引起您的问题。

10-07 15:09