python将脚本输出打印到csv或excel

时间:2018-02-28 17:53:04

标签: python

我知道有类似的问题,但我没有找到我需要的确切方案:

我有一个输出多个日期的python脚本,例如第一节代码:

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

并输出样本:(还有更多行)

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

在另一部分,我有一个循环,使用print语句等输出一些其他数据

如果不可能,我想将打印到屏幕上的所有数据导出到excel或csv中

至少,请告诉我如何除了上面的print语句,将数据添加到excel或csv文件

1 个答案:

答案 0 :(得分:0)

这可能会对你有帮助,

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