简体   繁体   中英

How to export data (which is as result of Python program) from command line?

I am working on a Python program, and I have results on the command line.

Now I need to do analysis on the results, so I need all results as exported in any format like either SQL, or Excel or CSV format.

Can some tell me how can i do that ?

import csv
x1=1 x2=2
while True:
    show = [ dict(x1=x1+1 , x2=x2+2)]
    print('Received', show )
    with open('large1.csv','w') as f1:
        writer=csv.writer(f1, delimiter=' ',lineterminator='\n\n',)
        writer.writerow(show)
    x1=x1+1
    x2=x2+1 

Here this is infinite loop and I want to have a csv file containing 2 column of x1 and x2. and with regularly updated all values of x1 and x2 row wise (1 row for 1 iteration)

But by this code I'm getting a csv file which is named as 'large1.csv' and containing only one row (last updated values of x1 and x2).

So how can I get my all values of x1 and x2 as row was in python.

Have a look at the open() documentation .

Mode w will truncate the file, which means it will replace the contents. Since you call that every loop iteration, you are continuously deleting the file and replacing it with a new one. Mode a appends to the file and is maybe what you want. You also might consider opening the file outside of the loop, in that case w might be the correct mode.

Just use the csv format it can easily imported into Excel and the python standard library supports csv out of the box. @See python-csv

One way to handle this is to use the CSV module , and specifically a Writer object to write the output to a CSV file (perhaps even instead of writing to stdout ). The documentation has several examples, including this one:

import csv
with open('some.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(someiterable)

You should then be able to import the CSV file easily in Excel if that is what you want.

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