[Python] Export to CSV issue only return the last data

Discussão em 'Python' iniciado por Stack, Julho 29, 2025.

  1. Stack

    Stack Membro Participativo

    I have my script here:

    import json
    import csv
    from pathlib import Path
    import os

    # Path
    downloads = os.path.expanduser("~/Downloads")
    json_path = os.path.join(downloads, "REB_ECC_THEMIS_DECISIONNEL_20250620020005.JSON")
    csv_path = os.path.join(downloads, "filtered_output.csv")

    # Load json file
    with open(json_path, "r", encoding="utf-8") as f:
    data = json.load(f)

    def flatten_json(obj, prefix=''):
    if isinstance(obj, dict):
    for k, v in obj.items():
    yield from flatten_json(v, f"{prefix}.{k}" if prefix else k)
    elif isinstance(obj, list):
    for i, item in enumerate(obj):
    yield from flatten_json(item, prefix)
    else:
    yield f"{prefix} = {json.dumps(obj)}"

    # Transform the file into a list and dict after
    liste = []
    for line in flatten_json(data):
    liste.append(line)
    rows = []
    fields = set()
    result = {}
    for item in liste:
    key, value = item.split("=", 1)
    result[key.strip()] = value.strip()
    # Send the data into a .csv
    with open(csv_path, "w", newline="") as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=result.keys())
    writer.writeheader()
    for row in [result]:
    writer.writerow(row)


    The problem is that the .csv only gives me the last row of data from the dict.

    I tried to implement a loop but it seems I need something to break line, so that the first row is the first data of the dict, 2nd row = 2nd data etc etc.

    Here is a part of the JSON file :

    [{"vbrk":{"vbeln":"0900997737","fkart":"ZF01","knumv":"0003120391","erdat":"2025-06-19","kunrg":"0299072264","kunag":"0087691105","zzcdepayspv":"FR","zztyppntvte":"","zzcdiatapvs":""},"vbrp":[{"vbrp":{"vbeln":"0900997737","posnr":"000010","fkimg":1.000,"aubel":"1001418224","aupos":"000010","matnr":"PT00","prodh":"00010001006000PTXX","werks":"1000","zzworkstationid":"87691105001","zzbegindatetimestamp":"20250603091653","zzdtdebuval":"2025-06-04","zzdtfinvali":"2025-06-04","zznurelzona":"","zznumrelakm":"","zzcdectrain":"","zznumetrain":"843921","zznbvoyageu":"000","zzcdprestat":"","zzcdprestar":"","zztyprencha":"","zzdiprencha":"","zztypededsv":"","zzcdcbezone":"","zzemultmod":"","zzcdecanefe":"","zznumseg":"01","zzcdiatapfr":"","zznuvoiture":"","zzcoulcalen":"","zzcdiataptv":"","zztyposvte":"Z10X","zztymachine":"38","zztypsuppor":"","zzclasse":"02","zzcdiatapdv":"","zzcdreductn":"","zzcdtarif":"","zzcduicdest":"87342014","zzcduicorig":"87313874","zzdistance":"00064","zzdtedepart":"2025-06-04","zzdurvalide":"","zzhredepart":"17:50:00","zzhrearrive":"","zzmtutilred":0,"zzmotifdsv":"","zznbpervald":"","zznbvoygrat":"000","zzcustomercardtype":"ZPAY","zzcustomercardvalidfrom":"","zzcustomercardvalidto":"","zzcdgot":"01","zzcanaldis":"200","zzcanaldist":"9","zzpalieresa":"","zzefattribu":"","zzdteemisdr":"","zzcdorgvoyg":"","zzclassecat":"002","zzefprestat":"1187","zzcdifictar":"","zztyparcour":"","zztytransac":"","zzefetablit":"","zzestemission":"","zztypidentf":"","zzefemettri":"","zzntprestat":"","zzdtearrive":"","zztyprelakm":"","zztransporteur":"0000022907","zznbvk":64.00,"zzcdterrit":"DO","zzcdbranchd":"10073","zzdistributeur":"64699","zzdivtransp":"18967","zzcdbrancht":"01500","zzcdrelakm":"","zzattributr":"","zztierprest":"","zzpartenaire":"","zzdistancet":"","zzdisctype":"","zzcdtypacc":"13","zzsousrela":"","zzindgamtrf":"02","zzindfer":"F","zzmvgr5":"","zznumimtran":"155805224","zztransactionsequencenumber":"MPD2500MBG6R1CFZ7QAP","zzcanalcom":"200","zzdivdistrb":"18962","zztypod":"01","zzcduicetrorig":"","zzcduicetrdest":"","zztvaterritdis":"01","zztvadactdis":"","zzparapproc":"","zztypequipm":"","zznbvoy":0,"zznbvkdom":"00000064","zztypevente":"V","zztrtypecd":"ZP01","zzreversalflag":"","zznumimtrvi":"","zzdatedeparttrajet":"2025-06-04","zzcduictrajd":"87342014","zzcduictrajo":"87313759","zzcdregiadm":"","zzcdregsncf":"","zzcduicovya":"","zzcduicdvya":"","zzcduicovyr":"","zzcduicdvyr":"","zzdthrdpvya":"","zzdthrdpvyr":"","zzsensvoy":""}


    and a screenshot of the expected CSV file:

    [​IMG]

    Continue reading...

Compartilhe esta Página