Milister
Milister

Reputation: 658

Python-Issue writing to CSV file

I can print results to terminal but unable to write to csv file

full file: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')

In csv file i get only headers, when uncomment print c i see lines are printed into terminal (output)

some of the lines from output:

ADFS-amtest-ro,pol-amtest-ro
adfs-host-role,pol-amtest-ro
aws-elasticbeanstalk-ec2-role,AWSElasticBeanstalkWebTier

Upvotes: 1

Views: 383

Answers (2)

Rehan Azher
Rehan Azher

Reputation: 1340

Please try code below:

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')

Your File writer is being opened in the loop and every time it was overwriting the file with only the headers. Simply moved it out.

Upvotes: 2

H. Gourlé
H. Gourlé

Reputation: 894

You should use csv.writer from the csv built-in module

in your example:

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)

Additionally, to incorporate Rehan's answer, the loop that is updating you s variable shouldn't be out there. The code blow should work for you:

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)

Upvotes: -1

Related Questions