[英]write csv rows one by one rather than all at once in python3 using writer.writerows(reader)
I am saving a csv file after skipping the rows before the 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
I am writing the remaining rows all at once to the file: 我将剩余的行一次全部写入文件:
try:
writer.writerows(reader) # remaining rows
except Exception as e:
print (e)
I would like to write the rows once by one because windows throws the following error: 'charmap' codec can't encode character '\\x83' in position 142: character maps to <undefined>
我想一次写一行,因为Windows抛出以下错误:
'charmap' codec can't encode character '\\x83' in position 142: character maps to <undefined>
It seems to be a windows issue, and since it happens so rarely, I would prefer to save the rows to the file one by one so only the problematic rows are skipped. 这似乎是Windows的问题,由于这种情况很少发生,因此我宁愿将行逐一保存到文件中,这样就只跳过有问题的行。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.