Create a .csv file with values from a Python list
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping
--
Chapters
00:00 Question
01:04 Accepted answer (Score 311)
01:29 Answer 2 (Score 124)
01:44 Answer 3 (Score 67)
02:04 Answer 4 (Score 40)
02:28 Thank you
--
Full question
https://stackoverflow.com/questions/2084...
Accepted answer links:
[see this SO answer]: https://stackoverflow.com/questions/3428...
Answer 3 links:
[DataFrame]: http://pandas.pydata.org/pandas-docs/sta...
[pandas]: http://pandas.pydata.org/
Answer 4 links:
[numpy]: http://docs.scipy.org/doc/numpy/referenc...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #csv #xlrd
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping
--
Chapters
00:00 Question
01:04 Accepted answer (Score 311)
01:29 Answer 2 (Score 124)
01:44 Answer 3 (Score 67)
02:04 Answer 4 (Score 40)
02:28 Thank you
--
Full question
https://stackoverflow.com/questions/2084...
Accepted answer links:
[see this SO answer]: https://stackoverflow.com/questions/3428...
Answer 3 links:
[DataFrame]: http://pandas.pydata.org/pandas-docs/sta...
[pandas]: http://pandas.pydata.org/
Answer 4 links:
[numpy]: http://docs.scipy.org/doc/numpy/referenc...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #csv #xlrd
#avk47
ACCEPTED ANSWER
Score 318
import csv
with open(..., 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)
Edit: this only works with python 2.x.
To make it work with python 3.x replace wb with w (see this SO answer)
with open(..., 'w', newline='') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)
ANSWER 2
Score 125
Here is a secure version of Alex Martelli's:
import csv
with open('filename', 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)
ANSWER 3
Score 40
The best option I've found was using the savetxt from the numpy module:
import numpy as np
np.savetxt("file_name.csv", data1, delimiter=",", fmt='%s', header=header)
In case you have multiple lists that need to be stacked
np.savetxt("file_name.csv", np.column_stack((data1, data2)), delimiter=",", fmt='%s', header=header)
ANSWER 4
Score 12
Use python's csv module for reading and writing comma or tab-delimited files. The csv module is preferred because it gives you good control over quoting.
For example, here is the worked example for you:
import csv
data = ["value %d" % i for i in range(1,4)]
out = csv.writer(open("myfile.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL)
out.writerow(data)
Produces:
"value 1","value 2","value 3"