如何将实时数据写入python中的csv文件 [英] how to write the real time data into csv file in python
问题描述
def event_handler_quote_update(message):
# print(f"quote update {message}")
global row_no
global token
global ltp
global Date
token = message['token']
ltp = message['ltp']
Date = message['exchange_time_stamp']
我需要将上述实时运行数据写入csv文件,目前,我的python脚本不会执行任何操作来写入csv文件.
i need to write the above live running data into csv file currently my python script will not do anything writing the csv file.
当前它正在处理excel文件,但是在从不同的脚本读取相同的excel时遇到了问题,因此我打算将数据写入csv文件中,
currently it is working with excel file, but i am having issue while reading same excel from different script, so i am planning to write the data into csv file,
推荐答案
无需在 global
中声明所有这些内容.当 def
之外的变量需要从内部进行更改时, global
声明非常有用且必要.
There is no need to declare any of those things global
. A global
declaration is useful and necessary when there is a variable outside of your def
which you need to change from inside.
要写入CSV数据,请使用 csv
库.
For writing CSV data, probably use the csv
library.
import csv
# ...
def event_handler_quote_update(message):
# print(f"quote update {message}")
token = message['token']
ltp = message['ltp']
date = message['exchange_time_stamp']
with open('results.csv', 'a+') as csvfile:
writer = csv.writer(csvfile)
writer.writerow([token, ltp, date])
如果有一种方法可以打开CSV文件以进行写入并实例化 writer
对象一次,那么只需在回调之外,然后简单地传入 writer ,那会好得多.code>作为
message
之后的第二个参数;不过,完成后,您将需要分别 close()
.
It would be a lot better if there was a way to open the CSV file for writing and instantiate the writer
object just once, outside the callback, and simply pass in writer
as the second argument after message
; though then, you will need to close()
it separately when you are done.
import csv
# ...
def event_handler_quote_update(message, writer):
# print(f"quote update {message}")
token = message['token']
ltp = message['ltp']
date = message['exchange_time_stamp']
writer.writerow([token, ltp, date])
# ...
if __name__ == '__main__':
# whatever else you have here
csvfile = open('results.csv', 'w')
writer = csv.writer(csvfile)
# ... whatever else your program needs to do
csvfile.close()
但是也许您无法控制回调的调用方式.那么也许您确实需要 writer
成为 def
中的 global
.
But maybe you don't have control over how the callback gets called. Then maybe you do need writer
to be global
inside the def
.
实际上不需要将每个字段都复制到一个单独的变量中;如果要提取很多字段,可能会切换到类似
There's no need really to copy each field into a separate variable; if there are a lot of fields you want to extract, probably switch to something like
writer.writerow([message[x] for x in ('token', 'ltp', 'exchange_time_stamp')])
如果您需要使用另一种CSV格式的变体(例如制表符或分号分隔,或在顶部写一个标题等),请参见上面的文档链接.
See the documentation link above if you need to use a different variant of CSV format, like tab or semicolon delimited, or write a header at the top, etc. It's all there.
这篇关于如何将实时数据写入python中的csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!