简体   繁体   中英

Python write list items to csv

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 ?

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

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)

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.

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).

with open('returns.csv', 'wb') as f:
    writer = csv.writer(f)
    for val in daily_returns:
        writer.writerow([val])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM