Reputation: 972
I have a list
like:
('so glad', 'happy')
('it is so sad', 'sad')
I want to write this lists into a CSV file like :
column1 column2
so glad happy
it is so sad sad
I used following code to do this:
with open('test.csv', "a") as outfile:
for entries in my_list:
outfile.write(entries)
outfile.write("\n")
But it writes into the CSV file as
column1
so glad
happy
it is so sad
sad
How can I make this code do as I expected?
Upvotes: 0
Views: 542
Reputation: 2652
For python 3: Use writerow to write a row taken from a list(iterable)
import csv
my_list =[('so glad', 'happy'),
('it is so sad', 'sad')]
with open('mycsv.csv','w+') as fileobj:
csvwriter = csv.writer(fileobj)
for row in my_list:
csvwriter.writerow(row)
or Use writerows which takes an iterable (an iterable is anything that can be used to iterate so your my_list
is an list iterable) and takes rows and saves them accordingly
import csv
my_list =[('so so glad', 'happy'),
('it is so sad', 'sad')]
with open('mycsv.csv','w+') as fileobj:
csvwriter = csv.writer(fileobj)
csvwriter.writerows(my_list)
For python 2:
with open('mycsv.csv','w+') as fileobj:
use wb instead of w+
The output in mycsv.csv
is:
so so glad,happy
it is so sad,sad
Also note i used w+ as mode here which truncates that is empties the csv file if already exists or creates a new one and writes content to them
There are several modes to write use one for your need. Take a look at the File modes documentation for python
On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files.
Upvotes: 1
Reputation: 5389
import csv
with open('test.csv', 'wb') as outfile:
wr = csv.writer(outfile, quoting=csv.QUOTE_ALL)
wr.writerow(entries)
Upvotes: 1