将API结果导出到CSV文件(定界正确的方法?)

时间:2018-10-26 20:34:44

标签: python api csv

我在将下面的API结果导出到csv文件时遇到麻烦。在我看来,分隔符是“,”(3个字符)。划定结果并创建干净的CSV文件的最佳方法是什么?

注意:此API可通过输入个人地址,名字,姓氏等来帮助确定个人地址是否最新。

CSV文件:

例如,如下图所示,导出的csv文件具有4个不同的单元格(还包含列名-AddressLine2)中分隔的4个地址值

(我最初输入4行。)

enter image description here

API结果(来自request.get):

  

{ “CASSReportLink”: “https://smartmover.melissadata.net/v3/Reports/CASSReport.aspx?tkenrpt=YvBDs39g52jKhLJyl5RgHKpuj5HwDMe1pE2lcQrczqRiG3/3y5yMlixj5S7lIvLJpDyAOkD8fE8vDCg56s3UogNuAkdTbS2aqoYF5FvyovUjnXzoQaHaL8TaQbwyCQ2RHVDSbt7tI8uGzEWwEIEwt6acz9MoXfDckO7OTUvVcuA=”, “NCOAReportLink”:“https://smartmover.melissadata.net/ V3 /报告/ NCOAReport.aspx tkenrpt = 8anQa424W7NYg8ueROFirapuj5HwDMe1pE2lcQrczqRiG3 / 3y5yMlixj5S7lIvLJpDyAOkD8fE8vDCg56s3UogNuAkdTbS2aqoYF5FvyovUjnXzoQaHaL8TaQbwyCQ2RHVDSbt7tI8uGzEWwEIEwt6acz9MoXfDckO7OTUvVcuA = “ ”记录?“:[{ ”AddressExtras“: ”“, ”AddressKey“: ”78704,78704“, ”AddressLine1“:”,STE C- 100“,” AddressLine2“:”“ 1009 W MONROE ST,1600 S 5TH ST,1008 W MILTON S T,3939 BEE CAVES RD“,” AddressTypeCode“:”“,” BaseMelissaAddressKey“:”“,” CarrierRoute“:”“,” City“:” Austin,Austin,Austin,Austin“,” CityAbbreviation“:” Austin,奥斯汀,奥斯汀,奥斯汀“,” CompanyName“:”“,” CountryCode“:” US“,” CountryName“:”美国“,” DeliveryIndi​​cator“:”“,” DeliveryPointCheckDigit“:”“,” DeliveryPointCode“:” “,” MelissaAddressKey“:”“,” MoveEffectiveDate“:”“,” MoveTypeCode“:”“,” PostalCode“:” 78704,78704,78704,78746“,” RecordID“:” 1“,”结果“:” AE07“,” State“:”“,” StateName“:” TX,TX ,TX,TX“,” Urbanization“:”“}],” TotalRecords“:” 1“,” TransmissionReference“:” 1353“,” TransmissionResults“:”“,” Version“:” 4.0.4.48“}   [在1.1秒内完成]

我的代码:

import requests
import json
import pandas as pd
import numpy as np


df = pd.read_csv(r"C:\users\testu\documents\travis_test.csv",delimiter = ',',na_values="nan")

url = 'https://smartmover.melissadata.net/v3/WEB/SmartMover/doSmartMover' 
payload = {'t': '1353', 'id': '138fg88jr3r', 'jobid': '1', 'act': 'NCOA, CCOA', 'cols': 'AddressLine1,AddressLine2,City,PostalCode,Results,State', 'opt': 'ProcessingType: Standard', 'List': 'test', 'full': df["appr_owner_name"], 'a1': df["prop_year_addr_line1"], 'a2': df["prop_year_addr_line2"], 'city': df["prop_addr_city"], 'state': df["prop_addr_state"], 'postal': df["prop_addr_zip"], 'ctry': 'USA'}

response = requests.get(
    url, params=payload,
    headers={'Content-Type': 'application/json'} # Using JSON here for readability in the response
)


r = response.text
print(r)

with open(r'C:\users\testu\documents\travis3.csv', 'w+') as f:
    f.write(r)

1 个答案:

答案 0 :(得分:0)

您的API返回值不是csv格式,而是json格式。 Tou不能只是将其写入文件中。

您实际上必须将其读取为json,提取数据并以所需的格式将其格式化为csv文件。示例:

r = response.json
with open(r'C:\users\testu\documents\travis3.csv', 'w+') as f:
    cf = csv.writer(f)
    cf.writerow(r['Records'][0]['AddressLine2'].split(','))