简体   繁体   中英

How do I get my python output into a csv or excel file?

for i in range(len(H)):
            S=Y[1:,(0,1,m)]  # change 2=> 2:m
            S=S[S[0:,0] ==HN[k]]
            S=S[S[0:,1] ==H[i]]
            S=S[S[0:,2]!=''] #
            S=S[0:,2]  #
            for j in range(len(S)):
                print(HN[k],H[i],S[j],H[j]*H[I])

This prints output of almost 900-1000 rows on my jupyter notebook. However I want output to be directly a csv or xls file. So that I don't have to copy or paste, would also save me time if rows increases of my data.

You can just do the following.

  • Open the file with csv.writer
  • write row wise the data in the writer
import csv

...

writer = csv.writer(open("/path/to/my/csv/file", 'w'))
for i in range(len(H)):
    S=Y[1:,(0,1,m)]  # change 2=> 2:m
    S=S[S[0:,0] ==HN[k]]
    S=S[S[0:,1] ==H[i]]
    S=S[S[0:,2]!=''] #
    S=S[0:,2]  #

    for j in range(len(S)):
        writer.writerow(HN[k], H[i], S[j], H[j]*H[i])

You can do something like this:

import csv

csvFile = open('example.csv', 'w')

with csvFile:
    writer = csv.writer(csvFile)
    for i in range(len(H)):
        S=Y[1:,(0,1,m)]
        S=S[S[0:,0] ==HN[k]]
        S=S[S[0:,1] ==H[i]]
        S=S[S[0:,2]!=''] #
        S=S[0:,2]  #
        for j in range(len(S)):
            writer.write('{},{},{},{}\n'.format(HN[k],H[i],S[j],H[j]*H[I]))

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