我可以将结果打印到终端,但无法写入 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
最佳答案
请尝试以下代码:
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')
您的文件编写器正在循环中打开,每次它都仅使用 header 覆盖文件。干脆就搬出去了。
关于Python-写入 CSV 文件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49710351/