使用writer.writerows(reader)在python3中逐个编写csv行而不是一次写入csv行

时间:2017-12-29 15:54:19

标签: python csv header

我在跳过标题之前的行后保存了一个csv文件:

                print (latest_file)
            with open(latest_file, "r",encoding="utf8") as infile:
                reader = csv.reader(infile)
                for row in reader:
                    #look for 
                    if row[0] == 'date/time':
                        print (row)
                        break
                else:
                    print("{} not found".format('name'))
                with open("C:/s3/"+str(p.from_date)+'_'+str(p.to_date)+'_'+str(merchant["country"])+'_'+str(merchant["company"])+'_'+"payments.csv", "w", newline='') as outfile:
                    writer = csv.writer(outfile)
                    writer.writerow(row) # headers

我正在将剩余的行一次性写入文件:

                    try:
                        writer.writerows(reader) # remaining rows
                    except Exception as e:
                        print (e)

我想逐个编写行,因为windows会抛出以下错误:'charmap' codec can't encode character '\x83' in position 142: character maps to <undefined>

这似乎是一个Windows问题,因为它很少发生,我宁愿将行逐个保存到文件中,因此只会跳过有问题的行。

1 个答案:

答案 0 :(得分:0)

for row in reader:  # the same reader used for reading
    try:
        writer.writerow(row) # remaining rows
    except Exception as e:
        print(row)
        print(e)
        print()