[英]Exporting REST Data to CSV in python
I have a python script that uses a function 'get_users' to gather data from a REST API, currently it simply prints to the console. 我從 GitHub 存儲庫中提取它,我正在嘗試對其進行修改以將該數據導出到 csv 但之前沒有與 Python 合作過。 csv 中的數據格式應該有:“用戶,Email,電話,推送,短信”。 這是代碼:
import argparse
import sys
def get_users(session):
sys.stdout.write("Listing All Users' Contact Methods:\n")
for user in session.iter_all('users'):
sys.stdout.write("User: ")
sys.stdout.write(user['name'])
sys.stdout.write("\n")
get_contact_methods(user['id'], session)
sys.stdout.write("-----\n")
get_users(session)
我嘗試在 function 末尾使用csv.writer(sys.stdout.write)
但收到 TypeError: argument 1 must have a "write" 方法
任何幫助,將不勝感激。
我認為您來自 Java,這就是您嘗試通過sys.stdout.write
使用控制台打印的原因。 在 python 中,您可以使用print
function 將某些內容打印到控制台,它自然會在其上附加一個換行符。 所以,它會是這樣的:
def get_users(session):
print("Listing All Users' Contact Methods:")
for user in session.iter_all('users'):
print("User: ")
print(user['name'])
print(user['id'], session)
print("-----")
get_users(session)
現在sys.stdout.write
是一個 function ,正如您所見,它將一個字符串打印到標准輸出。 類似地, csv.writer
是一個 function,它將文件作為輸入而不是 function。
所以你的新代碼將是:
#open file
file = open('rest.csv', 'w+', newline='')
#Notice how we pass the file as the argument
writer = csv.writer(file)
for user in session.iter_all('users'):
#First row which contains the headers
writer.writerow(["User","Email","Phone","Push","SMS"])
#Now write all the data
#I'm assuming the rest api returned a list of dictionary (json objects) in session
writer.writerow([user['name'],user['email'],user['phone'],user['push'],user['sms'])
file.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.