将字典导出到 csv 文件
export dictionary to csv file
我有一本像这样的字典
file = {"Formations" : ["some1","some2","some3"], "Depth": [1,2,3] }
我希望 "Formation" 和 "Depth" 成为 header,并希望该文件在我的输出 csv 文件中垂直列出。所以,
Formations Depth
some1 1
some2 2
some3 3
像这样。
如何做到这一点?如果有必要,我可以将深度列表 [1,2,3] 转换为字符串列表,例如 ["1", "2", "3"]。
对于 COLDSPEED,这是它在输出文件中的样子。
Formations Depth
(blank) (blank)
some1 1
(blank) (blank)
some2 2
(blank) (blank)
some3 3
(blank) 这里只是表示什么都没有的空行。我该如何解决这个问题?
您可以使用DictWriter
,但调用zip
然后将每一对写入您的CSV会更容易。
import csv
file = {"Formations" : ["some1","some2","some3"], "Depth": [1,2,3] }
with open(...) as f:
w = csv.writer(f)
for x, y in zip(file['Formations'], file['Depth']):
w.writerow([x, y])
我有一本像这样的字典
file = {"Formations" : ["some1","some2","some3"], "Depth": [1,2,3] }
我希望 "Formation" 和 "Depth" 成为 header,并希望该文件在我的输出 csv 文件中垂直列出。所以,
Formations Depth
some1 1
some2 2
some3 3
像这样。
如何做到这一点?如果有必要,我可以将深度列表 [1,2,3] 转换为字符串列表,例如 ["1", "2", "3"]。
对于 COLDSPEED,这是它在输出文件中的样子。
Formations Depth
(blank) (blank)
some1 1
(blank) (blank)
some2 2
(blank) (blank)
some3 3
(blank) 这里只是表示什么都没有的空行。我该如何解决这个问题?
您可以使用DictWriter
,但调用zip
然后将每一对写入您的CSV会更容易。
import csv
file = {"Formations" : ["some1","some2","some3"], "Depth": [1,2,3] }
with open(...) as f:
w = csv.writer(f)
for x, y in zip(file['Formations'], file['Depth']):
w.writerow([x, y])