Reputation: 171
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.
Upvotes: 1
Views: 2538
Reputation: 231395
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.
Upvotes: 3
Reputation: 77347
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))
Upvotes: 1