我可以将结果打印到终端但无法写入csv文件
完整档案:https://1drv.ms/u/s!AizscpxS0QM4hJo5SnYOHAcjng-jww
datapath = '1.json'
data = json.load(open(datapath))
with open('1.json') as file:
data = json.load(file)
for element in data['RoleDetailList']:
if 'RoleName' in element.keys():
s = element['RoleName']
#print s
with open('roleassign.csv', 'wt') as file:
file.write('Role,Policy\n')
for policy in element['AttachedManagedPolicies']:
c = s + ',' + policy['PolicyName']
#print c
file.write(c + '\n')
在csv文件中我只获取标题,取消注释print c
我看到行打印到终端(输出)
输出中的一些行:
ADFS-amtest-ro,pol-amtest-ro
adfs-host-role,pol-amtest-ro
aws-elasticbeanstalk-ec2-role,AWSElasticBeanstalkWebTier
答案 0 :(得分:2)
请尝试以下代码:
with open('output.json') as file:
data = json.load(file)
with open('roleassign.csv', 'wt') as file:
file.write('Role,Policy\n')
for element in data['RoleDetailList']:
if 'RoleName' in element.keys():
s= element['RoleName']
for policy in element['AttachedManagedPolicies']:
c = s + ',' + policy['PolicyName']
file.write(c + '\n')
您的文件编写器正在循环中打开,每次只用标题覆盖文件。简单地把它移出去了。
答案 1 :(得分:-1)
您应该使用csv内置模块中的csv.writer
:
with open('roleassign.csv', 'w') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
writer.writerow(['Role','Policy'])
for policy in element['AttachedManagedPolicies']:
c = [s, policy['PolicyName']]
writer.writerow(c)
此外,要结合Rehan的答案,更新s
变量的循环不应该在那里。代码打击应该对你有用:
with open('roleassign.csv', 'w') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
writer.writerow(['Role','Policy'])
for element in data['RoleDetailList']:
if 'RoleName' in element.keys():
s = element['RoleName']
for policy in element['AttachedManagedPolicies']:
c = [s, policy['PolicyName']]
writer.writerow(c)