简体   繁体   中英

python print the script output to csv or excel

I know that there are similar questions, but I didn't find the exact scenario that I need:

I have a python script which outputs multiple dates, for example in section one the code is:

print("All Subscriptions consumptions summary:")
for subscriptions in all_subscriptions_dic['results']:
        #getting  alist of variables from the function above 

       [subscription_name,subscription_type,available_sub,sub_consumed,sub_id]
        sub_details = subscriptions_list(subscriptions)
        redhat_subscriptions = rh_subs(sub_details[0])
        if sub_details[1] == 'NORMAL' and redhat_subscriptions:
                subscriptions_names_list.append(sub_details[0])

                print("\n" + 'Subscription name:' + " " + sub_details[0])
                print('Available_Subscriptions:' + " " + str(sub_details[2]))
                print('Consumed subscriptions:' + " " + str(sub_details[3]))

and sample output it: (there are much more lines)

All Subscriptions consumptions summary:

Subscription name: Red Hat Enterprise Linux Extended Life Cycle 
Available_Subscriptions: 4
Consumed subscriptions: 0

Subscription name: Red Hat Enterprise Linux Server for HPC
Consumed subscriptions: 0

On another section I have a loop which output some other data using print statement etc

I would like to export all the data that is printed to the screen, into excel or csv as well, if its not possible

at least ,please show me how to in addition to the above print statement ,add the data to excel or csv file

This may help you,

import csv

writer = csv.writer(open('subscriptions.csv', 'w'))
writer.writerow(['Subscription name', 'Available_Subscriptions:', 'Consumed subscriptions:'])

for sub_details in subscription_details:
    writer.writerow([sub_details[0]], sub_details[2], sub_details[3])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM