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

问题描述 投票:1回答:1

我在跳过标题之前的行后保存了一个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问题,因为它很少发生,我宁愿将行逐个保存到文件中,因此只会跳过有问题的行。

python csv header
1个回答
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()
© www.soinside.com 2019 - 2024. All rights reserved.