簡體   English   中英

用 Python 將 API 結果寫入 CSV

[英]Writing API Results to CSV in Python

我正在尋找使用 Python 將 API 結果寫入 .CSV 文件的一些幫助。 在這一點上,我成功寫入 .CSV,但我似乎無法確定我正在尋找的 .CSV 格式背后的代碼,這是標准的單字段 = 一列格式。

任何幫助表示贊賞! 詳情如下。 謝謝!

我的代碼:

import requests
import json
import csv

urlcomp = 'http://url_ommitted/api/reports/completion?status=COMPLETED&from=2016-06-01&to=2016-08-06'
headers = {'authorization': "Basic API Key Ommitted", 'accept': "application/json", 'accept': "text/csv"}

## API Call to retrieve report
rcomp = requests.get(urlcomp, headers=headers)

## API Results
data = rcomp.text

## Write API Results to CSV
with open('C:\_Python\\testCompletionReport.csv', "wb") as csvFile:
    writer = csv.writer(csvFile, delimiter=',')
    for line in data:
        writer.writerow(line)

上面的代碼創建了一個具有正確輸出的 .CSV 文件,但它將 API 結果中的每個字符寫入到輸出文件 A 列中的一個新單元格中。 截圖如下:

截圖如下:

我還嘗試了下面的代碼,它將整個 API 結果集寫入 .CSV 輸出文件中的單個單元格中。

代碼:

data = rcomp.text

with open('C:\_Python\\CompletionReportOutput.csv', 'wb') as csvFile:
    writer = csv.writer(csvFile, delimiter = ',')
    writer.writerow([data])

輸出:

在此處輸入圖片說明

下面是我的調用返回的一些示例 API 結果數據的屏幕截圖: 在此處輸入圖片說明

我在最終 .CSV 輸出文件中尋找的示例: 在此處輸入圖片說明

編輯 - 示例 API 響應:

“包裹已創建”、“包裹 ID”、“包裹名稱”、“包裹狀態”、“包裹已刪除”、“包裹已更新”、“寄件人 ID”、“寄件人姓名”、“寄件人公司”、“寄件人已創建”、 “發件人電子郵件”、“發件人姓名”、“發件人語言”、“發件人姓氏”、“發件人電話”、“發件人標題”、“發件人更新”、“發件人激活”、“發件人鎖定”、“發件人狀態”、 "SENDER TYPE" "Thu Aug 04 14:52:57 CDT 2016","ulw5MTQo8WjBfoCTKqz9LNCFpV4=","TestOne to TestTwo - Flatten PDF Removed","COMPLETED","false","Thu Aug 04 14:53:30 2016","tKpohv2kZ2oU","","","2016-08-03 14:12:06.904","testaccount@test.com","John","en","Smith",""," ","2016-08-03 14:12:06.942118","null","null","INVITED","REGULAR" "Thu Aug 04 09:39:22 CDT 2016","IJV3U_yjPlxS-TVQgMrsNgVU" "TestOne to TestTwo - 電子郵件測試","COMPLETED","false","Thu Aug 04 10:11:29 CDT 2016","tKpohv2kZ2oU","","","2016-08-03 14:12: 06.904","testaccount@test.com","John","en","Smith","","","2016-08-03 14:12:06.942118","null","null", “邀請”,“常規”

第二次編輯 - Lee 建議的輸出:

在此處輸入圖片說明

所以,我最終偶然發現了一個解決方案。 不確定這是否是處理此問題的“正確”方式,但下面的代碼將 API 結果直接寫入具有正確列格式的 .CSV。

# Get JSON Data
rcomp = requests.get(urlcomp, headers=headers)

# Write to .CSV
f = open('C:\_Python\Two\\newfile.csv', "w")
f.write(rcomp.text)
f.close()
csvFile = open('C:\_Python\\CompletionReportOutput.csv', 'w')

writer = csv.writer(csvFile, delimiter = ' ')

for row in data.split('\n'):
    writer.writerow(row)
import requests
import base64
import json

base_url = "http://dummy.restapiexample.com/api/v1/employees";

def get_report(base_url):
    print("Getting report results...")
    header_gs = {'Accept': 'application/json'}
    r = requests.get(base_url)
    if r.ok:
        print("Report results received...")
        print("HTTP %i - %s" % (r.status_code, r.reason))
        return r.text
    else:
        print("HTTP %i - %s" % (r.status_code, r.reason))

def export_to_json(base_url):
    print("Exporting report results to JSON file...")
    r = get_report(base_url)
    text_file = open("report_results.json", "w", encoding="utf8")
    text_file.write(r)
    text_file.close()

def export_to_csv(base_url):
    print("Exporting report results to JSON file...")

    csv_file = open('report_results.csv', "w", encoding="utf8")
    csv_file.write("Id, Employee_Name"+"\n") #manually modify this CSV file header
    csv_file.close()

    #there are 3 attributes in my example; add/remove levels according to the number of attributes in your case
    r = get_report(base_url)
    report_parsed = json.loads(r)
    print(report_parsed)
    a1_list = report_parsed['data']
    print(a1_list)
    for a1 in a1_list:
        a1_id = a1['id']
        a2_employee_name=a1['employee_name']
        csv_file = open('report_results.csv', "a", encoding="utf8")
        csv_file.write("'"+a1_id + "','" + a2_employee_name +"\n")
        csv_file.close()


    print("Export finished")

def main():
    choice = None
    while choice != "0":
        print \
            ("""
        ---MENU---
        
        0 - Exit
        1 - Export report results to JSON file
        2 - Export report results to CSV file
        """)

        choice = input("Your choice: ") # What To Do ???
        print()

        if choice == "0":
            print("Good bye!")
        elif choice == "1":
            export_to_json(base_url)
        elif choice == "2":
            export_to_csv(base_url)
        else:
            print(" ### Wrong option ### ")

### Main program
main()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM