导入CSV文件。迭代并过滤到JSON输出文件

时间:2020-03-23 17:53:39

标签: json python-3.x csv iteration

第一个问题。请帮忙。 我正在尝试使用3.7遍历CSV文件并以JSON格式输出一行。我可以打开CSV并打印所有行,但是JSON文件仅显示第一个。如何将所有内容写入JSON文件?

CSV文件如下:

Ad ID/ISCI,Ad ID/ISCI,Advertiser,Advertiser,Channel,Coverable label,Dropzone_status,House ID,House ID,Underlying Ad Found,Distinct count of Number of Records,Number of Records
AUSR0007H,AUSR0007H,Anheuser-Busch InBev,Anheuser-Busch InBev,AMCW,Not Coverable,Not Coverable,XC71508,XC71508,Ad Found,1,26
83JJ2004000H,83JJ2004000H,"Jimmy John's Enterprises, LLC","Jimmy John's Enterprises, LLC",AMCW,Not Coverable,Not Coverable,XC72833,XC72833,Ad Missing,1,24
HIHG0065H,HIHG0065H,Intercontinental Hotels Group Resources Inc,Intercontinental Hotels Group Resources Inc,AMCW,Not Coverable,Not Coverable,XC72628,XC72628,Ad Missing,1,22
YMGT0001000H,YMGT0001000H,Celgene Corporation,Celgene Corporation,AMCW,Not Coverable,Not Coverable,XC70495,XC70495,Ad Missing,1,20
WPJLSA30ELH,WPJLSA30ELH,Warby Parker,Warby Parker,AMCW,Not Coverable,Not Coverable,XC51192,XC51192,Ad Missing,1,15
QEBNERAC5B0H,QEBNERAC5B0H,Enterprise Rent A Car,Enterprise Rent A Car,AMCW,Not Coverable,Not Coverable,XC65094,XC65094,Ad Missing,1,13
YDEC1116000H,YDEC1116000H,Dell Computers,Dell Computers,AMCW,Not Coverable,Not Coverable,XC70296,XC70296,Ad Missing,1,2
YDEC1116000H,YDEC1116000H,Dell Computers,Dell Computers,AMCW,Coverable,Ad Missing,XC70296,XC70296,Ad Missing,1,11
ONTV0088500H,ONTV0088500H,Sherwin Williams/linking deals,Sherwin Williams/linking deals,AMCW,Not Coverable,Not Coverable,XC72371,XC72371,Ad Missing,1,11

代码:

import csv  
import json  

csvFilePath = 'Avails_Ad_Summary_data.csv'
jsonFilePath = 'warner_adids.json'
#reading csv and adding data to dictionary
data = {}
with open(csvFilePath) as csvFile:
    csvReader = csv.DictReader(csvFile, 'r')
    for csvRow in csvReader:
        data['Ad ID/ISCI'] = csvRow 
        print(csvRow)
        print(data)

#write to json file
with open(jsonFilePath, 'w') as jsonFile:
    jsonFile.write(json.dumps(data, indent=4))

JSON输出:

{
  "Ad ID/ISCI": {
    "r": "ZWHF0334000H",
    "null": [
        "ZWHF0334000H",
        "Whole Foods Market Inc./1920 UF + SWOP Simul",
        "Whole Foods Market Inc./1920 UF + SWOP Simul",
        "AMCW",
        "Not Coverable",
        "Not Coverable",
        "XC71769",
        "XC71769",
        "Ad Missing",
        "1",
        "1"
    ]
  }
}

0 个答案:

没有答案