[英]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. 我正在使用Python程序,并且在命令行上有结果。
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. 现在,我需要对结果进行分析,因此我需要将所有结果以任何格式导出,例如SQL,Excel或CSV格式。
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. 在这里,这是无限循环,我想要一个包含2列x1和x2的csv文件。 and with regularly updated all values of x1 and x2 row wise (1 row for 1 iteration)
并定期定期更新x1和x2的所有值(1行重复1次)
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). 但是通过这段代码,我得到了一个名为“ large1.csv”的csv文件,它仅包含一行(x1和x2的最新更新值)。
So how can I get my all values of x1 and x2 as row was in python. 因此,如何像python中那样获取x1和x2的所有值。
Have a look at the open() documentation . 看看open()文档 。
Mode w
will truncate the file, which means it will replace the contents. 模式
w
将截断文件,这意味着它将替换内容。 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. 模式
a
追加到文件, 可能就是您想要的。 You also might consider opening the file outside of the loop, in that case w
might be the correct mode. 您也可以考虑在循环外打开文件,在这种情况下,
w
可能是正确的模式。
Just use the csv format it can easily imported into Excel and the python standard library supports csv out of the box. 只需使用csv格式,它就可以轻松导入Excel,而python标准库开箱即可支持csv。 @See python-csv
@请参阅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
). 解决此问题的一种方法是使用CSV模块 ,特别是Writer对象 ,将输出写入CSV文件(甚至可以代替写入
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. 然后,如果需要的话,您应该可以轻松地在Excel中导入CSV文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.