My python version -3.6.9
。使用下面的python代码,我试图将json
响应写入csv
文件。
import requests
import json
import csv
user_list = '''robby.cornelissen
adrian.charles
tyler.swenson
brandon.miller
nathan.gallete'''
ports = [2316, 2340, 2380, 2482]
users = user_list.split('n')
fname = "result.csv"
with open(fname, "w") as file:
csv_file = csv.writer(file,lineterminator='n')
csv_file.writerow(["depotFile", "host", "isgroup", "line", "perm", "unmap", "user"])
for user, port in zip(users, ports):
print(f'from csv and other method here is the user and port: {user}, {port}')
url = f'http://198.98.99.12:46567/{port}/protects/{user}'
print(f'grab data from rest api: {url}')
response = requests.get(url, auth=('tool-admin', 'password'))
data = requests.get(url).json()
for item in list(data):
csv_file.writerow(item.values())
当前输出:-
depotFile host isgroup line perm unmap user
//LIB/Include/... * 12 read 2G_Members
//Prj/LIB/... * 15 write 4G_Members
//AND/KIO/... * 16 read 5G_Members
//PRJ/MM/SRC/... * 17 write 4G_Members
//Hon/Sam/... * 18 read 6G_Members
当前问题如下,
在传递多个用户id的
user_list
段和传递多个端口号的ports
段中,但目前它只写单个用户id的响应。但是它需要为所有提供的用户列表逐一编写响应。同样在
output csv
文件中需要user_list
和ports
的额外两列。例如({port} & {user}
需要附加在csv文件中)。
预期输出:-
depotFile host isgroup line perm unmap user user_list port
//LIB/Include/... * 12 read 2G_Members robby.cornelissen 2316
//Prj/LIB/... * 15 write 4G_Members adrian.charles 2316
//AND/KIO/... * 16 read 5G_Members tyler.swenson 2340
//PRJ/MM/SRC/... * 17 write 4G_Members brandon.miller 2380
//Hon/Sam/... * 18 read 6G_Members nathan.gallete 2482
需要帮助来解决这个问题。提前谢谢。
需要将user
和port
添加到每个data
行
for item in data:
item = list(item.values()) + [user, port]
csv_file.writerow(item)