简体   繁体   English

Python字典到csv excel

[英]Python dictionary to csv excel

I try to get a csv from my dictionary in python. 我尝试从python中的字典中获取csv。

I can create a csv file and put my dictionary in it. 我可以创建一个csv文件并将我的字典放入其中。

The problem is that when I open the file with excel the header and the values are in one column, but I want all keys and all values in separate columns. 问题是,当我用excel打开文件时,标题和值在一列中,但我希望所有键和所有值都在不同的列中。

For example: 例如:

      column1 column2 column3        column4
row 1 "name"   "temp" "tempeinheit"  "Druck"
row 2 "test"   24      "C"             0.1 

This is the following code. 这是以下代码。

dict= [{"name" : "test", "temp" : 24, "tempeinheit": "C", "druck" : 0.1,    "druckeinheit": "Pa"},{"name" : "benni", "temp" : 24, "tempeinheit": "C", "druck" : 0.1, "druckeinheit": "Pa"}]
with open("C:\\test#\\test.csv","w",newline='') as csvfile:

writer = csv.writer(csvfile,dialect="excel-tab")

for row in dict:
    if count == 0:
        header=row.keys()
        writer.writerow(header)
        count=+1
    writer.writerow(row.values())

Update: 更新:

I just convert the Dictionary in 2 Lists. 我只是在2个列表中转换字典。 One for the keys and one for the data, and I wrote them with the writer.writerow(Data). 一个用于键,一个用于数据,我用writer.writerow(Data)编写它们。

The other thing is, I use excel 2013 and for a new column it's not delimiter="," but the delimiter=";". 另一件事是,我使用excel 2013和新列,它不是delimiter =“,”但是delimiter =“;”。 so the ";" 所以 ”;” tells excel to put the data into a new column. 告诉excel将数据放入新列。

Thanks for the help. 谢谢您的帮助。

I tried running your code and following problems were found. 我尝试运行您的代码,发现以下问题。

  • Import CSV error 导入CSV错误
  • File was closed when you tried to write to it through the code. 当您尝试通过代码写入文件时,文件已关闭。
  • count variable was not initialized. count变量未初始化。

I haved added here my working code. 我在这里添加了我的工作代码。 Please let me know if you face any issue. 如果您遇到任何问题,请告诉我。

import csv
dict= [{"name" : "test", "temp" : 24, "tempeinheit": "C", "druck" : 0.1,    "druckeinheit": "Pa"},
    {"name" : "benni", "temp" : 24, "tempeinheit": "C", "druck" : 0}]
with open("try.csv","a") as csvfile:
    writer = csv.writer(csvfile,dialect="excel-tab")
    count = 0
    for row in dict:
        if count == 0:
            header=row.keys()
            writer.writerow(header)
            count=+1
        writer.writerow(row.values())

You can try like so with pandas: 您可以尝试使用pandas:

import pandas as pd

d = [{"name" : "test", "temp" : 24, "tempeinheit": "C", "druck" : 0.1,    "druckeinheit": "Pa"},
     {"name" : "benni", "temp" : 24, "tempeinheit": "C", "druck" : 0.1, "druckeinheit": "Pa"}] 

df = pd.DataFrame(d)

df = df[['name', 'temp', 'tempeinheit', 'druck','druckeinheit']]
df.to_csv('filename')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM