shiv mehra
shiv mehra

Reputation: 21

Python - Append to CSV

I am trying to append to a CSV file with the following code

import csv
cat_options = [row for row in csv.reader(open('catOptions.csv', 'r'), delimiter =',')]
print cat_options
new_cat = raw_input("\nEnter the new category: ")
cat_options = csv.writer(open('catOptions.csv', 'a'))
cat_options = cat_options.writerows(new_cat)

Following is the output: "Housing" "Transportation" S a v i n g s

The file "catOptions.csv" has Housing and Transportation. I tried to append Savings and did not get the desired result. Each word appears on a separate line. However the following code gives me the desired result but i am curious to know if there is an efficient way to do this.

import csv
cat_options = [row for row in csv.reader(open('catOptions.csv', 'r'), delimiter =',')]
print cat_options
new_cat = []
new_cat.append(raw_input("\nEnter the new category: "))
cat_options = csv.writer(open('catOptions.csv', 'a'))
cat_options = cat_options.writerows([new_cat])

Thanks in advance!

Upvotes: 2

Views: 3254

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798446

Use csvwriter.writerow() if you only want to write a single row.

Upvotes: 5

Related Questions