Trying to append csv into another csv AS A ROW but I am getting this AttributeError: '_io.TextIOWrapper' object has no attribute 'writerows'

Question:

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)
Asked By: bananas

||

Answers:

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)
Answered By: JayPeerachai
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.