My python version -3.6.9
. With the below python code I'm trying to write the json
response into csv
file.
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())
Current Output:-
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
Current problem as follows,
In the
user_list
section passing multiple user ids and inports
section passing multiple port numbers, however currently it is writing response of single user-id only. But it need to write response for all provided users list one by one.Also in the
output csv
file would need additional two columns withuser_list
andports
. I.e.({port} & {user}
need to append in csv file).
Expected output:-
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
Need help to fix this. Thanks in advance.
CodePudding user response:
You need to add user
and port
to each data
row.
for item in data:
item = list(item.values()) [user, port]
csv_file.writerow(item)