Reputation: 88
I'm reading and parsing lines from a flat text file. I take certain values from that file, do some minor formatting/conversion steps, and spit out a comma separated string. Up until now, I've been just writing those strings straight into a new csv file. However, now I'm trying to utilize the csv library to handle that more effectively.
import csv
mydata = ["This, is, a, test, row",
"This is, another test, row, my, dude",
"100, 200, 300, 400, 500"]
with open('test.csv', 'w') as target:
writer = csv.writer(target, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(mydata)
Results in this:
"This, is, a, test, row","This is, another test, row, my, dude","100, 200, 300, 400, 500"
Not really what I'm looking for. Whereas writer.writerows(mydata)
results in this:
T,h,i,s,",", ,i,s,",", ,a,",", ,t,e,s,t,",", ,r,o,w
T,h,i,s, ,i,s,",", ,a,n,o,t,h,e,r, ,t,e,s,t,",", ,r,o,w,",", ,m,y,",", ,d,u,d,e
1,0,0,",", ,2,0,0,",", ,3,0,0,",", ,4,0,0,",", ,5,0,0
Based on what I can tell, csv.writer()
is either iterating through a list of strings (the first example) or a string of characters (the second example). I've also tried iterating through each item in mydata
with a for loop, but that hasn't helped eiter. For the life of me, I can't figure out the best way to use the writer to parse this data so that each item in my list corresponds to a row in my target csv file. Would it make sense to store the mydata
data in a completely different data structure? What's the best way to handle this?
Upvotes: 2
Views: 6774
Reputation: 1508
Make my data a two-dimensional list, and user writer.writerows()
import csv
mydata = [['This', 'is', 'a', 'test', 'row'],
['This', 'is', 'another', 'test', 'row', 'my', 'dude'],
['100', '200', '300', '400', '500']]
with open('test.csv', 'w') as target:
writer = csv.writer(target)
writer.writerows(mydata)
writerow() is best used for writing single lines, like headers:
import csv
myheaders = ['Header1', 'Header2', 'Header3', 'Header4', 'Header5']
mydata = [['This', 'is', 'a', 'test', 'row'],
['This', 'is', 'another', 'test', 'row', 'my', 'dude'],
['100', '200', '300', '400', '500']]
with open('test.csv', 'w') as target:
writer = csv.writer(target)
writer.writerow(myheaders)
writer.writerows(mydata)
Upvotes: 4
Reputation: 2682
You need to use writerows
with a list of lists, like so:
import csv
mydata = [["This, is, a, test, row"],
["This is, another test, row, my, dude"],
["100, 200, 300, 400, 500"]]
with open('test.csv', 'w') as target:
writer = csv.writer(target, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerows(mydata)
Your current code is treating each string as a list of columns, hence the unexpected output.
Upvotes: 2