您好我正在尝试创建一个类似于此的股票CSV表格(为简单起见,数字设置为相同):
symbol ev_ebitda asset
msft 40 60
cvx 40 60
baba 40 60
我有一个股票代码清单(将在稍后的时间点扩展):
symbol = ["msft", "cvx", "baba"]
我为每个符号创建了一个字典,其中'symbol'
,'ev_ebitda'
和'asset'
为关键字:
i=0
while i <len(symbol):
vars()[symbol[i]] = {}
vars()[symbol[i]]['symbol']=symbol[i]
vars()[symbol[i]]['ev_ebitda'] = 40
vars()[symbol[i]]['asset'] = 60
i +=1
例如:
cvx = {'asset': 60, 'ev_ebitda': 40, 'symbol': 'cvx'}
然后我尝试使用以下代码输出表:
header = ["symbol","ev_ebitda","asset"]
f = open('output.csv', 'wb')
w =csv.DictWriter(f, fieldnames = header)
w.writeheader()
w.writerow() #not sure what to put in here
我不确定如何从多个词典中写入多行。我尝试按照discussion中的方法进行操作,但没有成功。我一直在努力解决过去8小时的问题,非常感谢你的帮助!这是我的完整代码:
import csv
symbol = ["msft", "cvx", "baba"]
header = ["symbol","ev_ebitda","asset"]
#create dictionary from the symbol list
i=0
while i <len(symbol):
vars()[symbol[i]] = {}
vars()[symbol[i]]['symbol']=symbol[i]
vars()[symbol[i]]['ev_ebitda'] = 40
vars()[symbol[i]]['asset'] = 60
i +=1
#output csv
f = open('output.csv', 'wb')
w =csv.DictWriter(f, fieldnames = header)
w.writeheader()
w.writerow(cvx)
答案 0 :(得分:0)
当您使用DictWriter
时,您需要按如下方式构造每行字典:
import csv
symbol = ["msft", "cvx", "baba"]
header = ["symbol","ev_ebitda","asset"]
with open('output.csv', 'wb') as f_output:
csv_output = csv.DictWriter(f_output, fieldnames=header)
csv_output.writeheader()
for s in symbol:
row = {'asset': 60, 'ev_ebitda': 40, 'symbol': s}
csv_output.writerow(row)
这将创建一个输出CSV文件,如下所示:
symbol,ev_ebitda,asset
msft,40,60
cvx,40,60
baba,40,60