d = { 'A': 85, 'B':70, 'C':40}
I need to write it as a .csv file with the title "title,score"
I tried two methods, but both of them do not work.
#Method 1:
f= open('score.csv','w')
f.write('Title,Score\n')
a = str(d)
for item in a.strip('{}').split(','):
item.replace(':',',')
f.write(item)
f.close()
#When I open score.csv, I do not know why it shows nothing.
#Method 2:
f= open('score.csv','w')
f.write('Title,Score\n')
with open('score.csv','w') as f:
for title in d.keys():
f.write('%s,%s\n'%(title,str(d[title]))
#method 2 cannot run, I guess it is because I cannot write the number in the file? But I tried str, it still cannot run.
CodePudding user response:
Using pandas can do the task in single line
pip install pandas
Logic
import pandas as pd
d = { 'A': 85, 'B':70, 'C':40}
(pd.DataFrame.from_dict(data=d, orient='index')
.to_csv('dict_con.csv', header=False))
output csv#
CodePudding user response:
The second iteration of your code, "Method 2", is what you want. The reason it is "not running" is because of this line:
f.write('%s,%s\n'%(title,str(d[title]))
The error you get is "unexpected end of file", and your program file is listed as the file. If you look closely you'll see that you have three open parentheses, but you have only two closed parentheses. Add a parenthesis and it almost works perfectly. What's still holding it back a bit is this:
f= open('score.csv','w')
f.write('Title,Score\n')
You're opening the file as f
, writing to it, then -- without closing it -- opening another file as f
, and writing new data. The buffer from the first f
file object never gets written to the file so you never get the headers as part of your CSV file.
These minor modifications to your code will do the trick:
d = { 'A': 85, 'B':70, 'C':40}
# f= open('score.csv','w') #don't need this
with open('score.csv','w') as f:
f.write('Title,Score\n') #moved from above
for title in d.keys():
f.write('%s,%s\n'%(title, d[title])) #don't need the str()
I forgot: you don't need that str()
in f.write()
.
CodePudding user response:
For writing a .CSV file, use the csv
module. Make sure to use the newline=''
parameter as documented. See this answer for why.
It doesn't matter for this simple example, but the csv
module will also properly quote fields containing the column separator and escape embedded quotes. Don't re-invent the wheel and try to write a CSV manually.
import csv
d = {'A': 85, 'B': 70, 'C': 40}
with open('score.csv', 'w', newline='') as fout:
writer = csv.writer(fout)
writer.writerow(['title', 'score'])
for key, value in d.items():
writer.writerow([key, value])
# CSV module will properly quote and escape fields as needed
writer.writerow(['field,with,commas','field"with"quotes'])
score.csv:
title,score
A,85
B,70
C,40
"field,with,commas","field""with""quotes"
Excel:
CodePudding user response:
An oversimplified but working solution:
csv_string = "\n".join(",".join(map(str, pair)) for pair in d.items())
#'A,85\nB,70\nC,40'
Then write the csv_string
to a file.