i am trying to append the content in one of my CSV as a ROW to another csv but i am getting this attribute error...I am unsure how to fix it. I think the issue is with writer.writerows(row) but I don't what i should change it to for .writerows(row) to work
This is my below code for appending the first csv to the second csv.
with open(csv1', 'r', encoding='utf8') as reader, open(csv2', 'a', encoding='utf8') as writer:
for row in reader:
writer.writerows(row)
CodePudding user response:
Use write() instead because writerows() is belong to csv.writer, not normal io. However, if you want to append at the end of the file, you need to make sure that the last row contain new line (i.e., \n) already.
with open('test1.csv', 'r', encoding='utf8') as reader:
with open('test2.csv', 'a', encoding='utf8') as writer:
writer.write("\n") # no need if the last row have new line already
for line in reader:
writer.write(line)
Or, if you want to use csv, you can use writerows() as shown in code below:
import csv
with open('test1.csv', 'r', encoding='utf8') as reader:
with open('test2.csv', 'a', encoding='utf8') as writer:
csv_reader = csv.reader(reader)
csv_writer = csv.writer(writer)
csv_writer.writerow([]) # again, no need if the last row have new line already
csv_writer.writerows(csv_reader)
