Reputation: 217
I have this code which suppose to export my list items to a csv file where each row in the file contains an item in the list.
writer = csv.writer(open(path+"output.csv", 'wb'))
for item in result:
writer.writerow(item)
THe result I'm getting is quite strange (example for the 2 top items in the list: 'past due' and 'code'):
p,a,s,t, ,d,u,e
c,o,d,e
The results I want to get is simply:
past due
code
Any ideas ?
Upvotes: 0
Views: 7063
Reputation: 1097
with open('returns.csv', 'wb') as f:
writer = csv.writer(f)
for val in daily_returns:
writer.writerow([val])
Upvotes: 0
Reputation: 25023
The writerow
method accepts a single argument and writes a comma separated representation of the elements that constitute its argument.
Usually the argument that is used is a list, a tuple, etc. Apparently you used a string, and hence what was written is the sequence of the elements of the string
If all the elements on which you want to iterate are strings, this would do the trick
for item in result:
writer.writerow([item])
but writing a csv file containing just a column is unusual and it is possible that you may want to write a simple text file... If all the elements in result
are strings thew following code
with of as open('result.txt')
of.write("\n".join(result))
will do the job.
Upvotes: 1
Reputation: 1551
csvwriter.writerow(row)
This will write the row parameter to the writer’s file object, formatted according to the current dialect.
For more Info See the csvwriter
Upvotes: 2
Reputation: 3480
I think the problem is here:
for item in result:
writer.writerow(item)
The result
variable is actually a string, which is why it's adding a comma after every character. result
isn't an array of strings like your code suggests--it's actually a string (an array of characters).
Upvotes: 0
Reputation: 759
There is already a solution for that here: Writing List of Strings to Excel CSV File in Python
You don't need to iterate through each element in the list. Try this:
writer = csv.writer(open(path+"output.csv", 'wb'))
writer.writerow(result)
Upvotes: 1