Python-Issue写入CSV文件

时间:2018-04-07 18:01:42

标签: python csv

我可以将结果打印到终端但无法写入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

2 个答案:

答案 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)