【问题标题】:CSV to JSON using loopCSV 到 JSON 使用循环
【发布时间】:2021-11-03 23:24:54
【问题描述】:

我编写了一个将 CSV 转换为 JSON 的程序。我为每一列一次又一次地编写相同的代码。

import csv, json
from os import read

#--------- COLUMN-1------------#
with open ("newsample2.csv", "r") as f:
    reader = csv.reader(f)
    next(reader)    
    data0 = {
        "Enabled": True,
        "Stops": []
        }
    for row in reader:
       data0["Stops"].append({"Symbols":row[0]})

#--------- COLUMN-2------------#
with open ("newsample2.csv", "r") as f:
    reader = csv.reader(f)
    next(reader)
    data1 = {
        "Enabled": True,
        "Stops": []
        }
    for row in reader:
       data1["Stops"].append({"Symbols":row[1]})

#--------- COLUMN-3------------#
with open ("newsample2.csv", "r") as f:
    reader = csv.reader(f)
    next(reader)
    data2 = {
        "Enabled": True,
        "Stops": []
        }
    for row in reader:
       data2["Stops"].append({"Symbols":row[2]})

#--------- COLUMN-4------------#
with open ("newsample2.csv", "r") as f:
    reader = csv.reader(f)
    next(reader)
    data3 = {
        "Enabled": True,
        "Stops": []
        }
    for row in reader:
       data3["Stops"].append({"Symbols":row[3]})

#--------- COLUMN-5------------#
with open ("newsample2.csv", "r") as f:
    reader = csv.reader(f)
    next(reader)
    data4 = {
        "Enabled": True,
        "Stops": []
        }
    for row in reader:
       data4["Stops"].append({"Symbols":row[4]})

root = {}
root["base_strip1"] = data0
root["base_strip2"] = data1
root["base_strip3"] = data2
root["base_strip4"] = data3
root["base_strip5"] = data4

main_root = {}
main_root["ReelStripsDefinition"] = root

with open ("json1.json", "w") as f:
    json.dump(main_root, f, indent=4)

有没有什么可以使用循环来缩短这段代码。

CSV 文件:https://drive.google.com/file/d/19u8M0wFrUq8E9um3l6sw0UZeQZRWTxNb/view?usp=sharing

JSON 格式:https://drive.google.com/file/d/1FyG7gG31FzvQECx1nP0VKsd84bOQ3pOy/view?usp=sharing

尝试的代码:

import csv, json
from os import read

with open ("newsample2.csv", "r") as f:
    reader = csv.reader(f)
    next(reader)
    for data in reader:
        for i in range(5):    
            data[i] = {
                "Enabled": True,
                "Stops": []
                }
            for row in reader:
                data[i]["Stops"].append({"Symbols":row[i]})

root = {}
root["base_strip1"]
main_root = {}
main_root["ReelStripsDefinition"] = root

with open ("jsonloop.json", "w") as f:
    json.dump(main_root, f, indent=4)

【问题讨论】:

  • 你研究过或尝试过将重复的代码写成循环吗?
  • 当我使用循环时,我没有得到上面共享的 JSON 格式的数据。 PS:我想要的只是不要只为 5 列编写相同的代码 5 次
  • 我的意思是,你读过 Python 教程吗?请先通过tutorial 并努力创建一个循环,然后再用代码提出问题,如果您仍然卡住,请显示您的尝试。
  • 我确实试过了,但无法得到结果。如果您很难相信我可以添加我尝试过的代码。
  • 是的,请,因为显示您的非工作代码是我们可以看到您可能遇到的问题并提供帮助的唯一方法。

标签: python json csv


【解决方案1】:

尝试以下方法:

import csv, json
from os import read

with open ("newsample2.csv", "r") as f:
    reader = csv.reader(f)
    next(reader)    
    
    data = [{"Enabled": True, "Stops" : []} for _ in range(5)]
    
    for row in reader:
        for col in range(5):
            data[col]["Stops"].append({"Symbols" : row[col]})

main_root = {"ReelStripsDefinition" : {f"base_strip{bs}" : item for bs, item in enumerate(data, start=1)}}

with open ("json1.json", "w") as f:
    json.dump(main_root, f, indent=4)

诀窍是使用列表而不是特定的变量名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 2020-02-24
    • 2021-04-10
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多