简体   繁体   中英

Pandas how to save a list to csv

I have a list in pandas and I want to write it to a csv file where each element is a new row.

    list3= ["France","Germany","USA"]
    with open('your_file.csv', 'w') as f:
        f.write(str(list3))

But the output is horizontal instead of vertical and if anyone knows how to get rid of the quotation marks in the output I would appreciate that too.

Output with my above code: 在此处输入图像描述

Output that I want: 在此处输入图像描述

This is a Python list, no pandas in sight.

In [26]: list3= ["France","Germany","USA"]                                      

Look at what str produces:

In [27]: str(list3)                                                             
Out[27]: "['France', 'Germany', 'USA']"

That is one string with brackets and quotes.

What you want is more like:

In [28]: for word in list3: print(word)                                         
France
Germany
USA

Or writing the same to a file:

In [29]: with open('txt', 'w') as f: 
    ...:     for word in list3: 
    ...:         f.write('%s\n'%word) 
    ...:                                                                        
In [30]: cat txt                                                                
France
Germany
USA

Or with print file parameter:

In [31]: with open('txt', 'w') as f: 
    ...:     for word in list3: 
    ...:         print(word, file=f) 

or you can join the strings newlines:

In [33]: '\n'.join(list3)                                                       
Out[33]: 'France\nGermany\nUSA'
In [34]: with open('txt', 'w') as f: 
    ...:     print('\n'.join(list3), file=f) 

You could put the list in pandas DataFrame , but then you have to turn off columns and indices when writing the csv.

numpy also does it with np.savetxt('txt',list3, fmt='%s') .

Lots of ways of writing such a basic list of strings to a file. Some basic, some using more powerful writers.

This can be done with the CSV module. Each row must be a list but you can generate them for the csv writer, one per item in your list

import csv
list3= ["France","Germany","USA"]
with open('your_file.csv', 'w') as f:
    csv.writer(f).writerows([row] for row in list3)

Output

France
Germany
USA

You may not need the CSV module at all. This will also write the list. The difference is that the first example would also escape internal quotes and commas, if that's a thing in your data.

import csv
list3= ["France","Germany","USA"]
with open('your_file.csv', 'w') as f:
    f.write("\n".join(list3))

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