Matthew Pearson
Matthew Pearson

Reputation: 31

Writing an array to a CVS file in python

I sincerely apologies if this is an already answered question, I have looked at many resources already and all either make no sense to me or only work in python 2x.

So basically, I have a list which the user appends.

print("\nPlease enter all relevant information\n")
A = []
A.append(input("thing: "))
A.append(input("thing2 : "))
A.append(input("etc : "))

I want to add all this information into an imported cvs file (which already has several lines) so it would be on a new row and would look something like this

thing,thing2,etc

This is the code I have for this

f  = open('Datafile.csv', "wb")
datafile = csv.writer(f, delimiter=',')

for item in A:
    datafile.writerow(item)    

f.close()

but it doesn't seem to work

error =

File "Filepath", line 57, in new
datafile.writerow(item)
TypeError: 'str' does not support the buffer interface

Upvotes: 0

Views: 93

Answers (2)

Francisco
Francisco

Reputation: 11496

writerow accepts a list, tuple or dict as its argument, not a string, do this instead:

datafile.writerow(A)

You're also opening your file in 'wb' mode, and you want to append to it, use 'a' instead:

f  = open('Datafile.csv', "a")

Upvotes: 2

Joran Beasley
Joran Beasley

Reputation: 114108

for item in A:
    datafile.writerow(item)    

should just be

datafile.writerow(A)    

Upvotes: 1

Related Questions