Json响应没有将提供的用户写入csv文件



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  

当前问题如下,

  1. 在传递多个用户id的user_list段和传递多个端口号的ports段中,但目前它只写单个用户id的响应。但是它需要为所有提供的用户列表逐一编写响应。

  2. 同样在output csv文件中需要user_listports的额外两列。例如({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

需要帮助来解决这个问题。提前谢谢。

需要将userport添加到每个data

for item in data:
item = list(item.values()) + [user, port]
csv_file.writerow(item)

相关内容

  • 没有找到相关文章

最新更新