【发布时间】:2018-10-02 13:08:39
【问题描述】:
我有一个 excel 文件,其中数据以 csv 格式以这种方式保存。该数据存在于 excel 文件中,如下所示,在 A 列下(CSV 文件由我编写的 LabView 软件代码生成生成数据)。我还在我的问题末尾附上了 csv 文件的图像以供参考。
RPM,Load Current,Battery Output,Power Capacity
1200,30,12,37
1600,88,18,55
我想创建一个这种格式的 Json 文件
{
"power_capacity_data" :
{
"rpm" : ["1200","1600"],
"load_curr" : ["30","88"],
"batt_output" : ["12","18"],
"power_cap" : ["37","55"]
}
}
这是我的代码
import csv
import json
def main():
#created a dictionary so that i can append data to it afterwards
power_data = {"rpm":[],"load_curr":[],"batt_output":[],"power_cap":[]}
with open('power1.lvm') as f:
reader = csv.reader(f)
#trying to append the data of column "RPM" to dictionary
rowcount = 0
for row in reader:
if rowcount == 0:
#trying to skip the first row
rowcount = rowcount + 1
else:
power_data['rpm'].append(row[0])
print(row)
json_report = {}
json_report['pwr_capacity_data'] = power_data
with open('LVMJSON', "w") as f1:
f1.write(json.dumps(json_report, sort_keys=False, indent=4, separators=(',', ': '),encoding="utf-8",ensure_ascii=False))
f1.close()
if __name__ == "__main__":
main()
我得到的输出 json 文件是这样的:(请忽略我代码中的 print(row) 语句)
{
"pwr_capacity_data":
{
"load_curr": [],
"rpm": [
"1200,30,12.62,37.88",
"1600,88,18.62,55.88"
],
"batt_output": [],
"power_cap": []
}
}
整行都保存在列表中,但我只想保存 RPM 列下的值。有人可以帮我解决我可能做错的事情吗。提前致谢。I have attached an image of csv file to just in case it helps
【问题讨论】: