file.write with Python接收错误消息connectionClosed

2024-06-01 00:31:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有正在工作的Python脚本,我正在尝试修改它。脚本获取股票的价格并在Python控制台中打印出来。我试图改变这个写价格的文本文件。以下是原始代码:

类BerryWrapper(EWrapper):

def __init__(self):

    pass

def tickPrice(self, tickerId, field, price, canAutoExecute):

    if (field == 4):

        print 'Last[%s,%s,%s]' % (tickerId, price, canAutoExecute)

    elif (field == 1):

        print 'Bid[%s,%s,%s]' % (tickerId, price, canAutoExecute)

    elif (field == 2):

        print 'Ask[%s,%s,%s]' % (tickerId, price, canAutoExecute)

这似乎很管用。我将其修改为:

类BerryWrapper(EWrapper):

def __init__(self):

    pass

with open('log_me.txt','w') as file:

    def tickPrice(self, tickerId, field, price, canAutoExecute):

        if (field == 4):

            print 'Last[%s,%s,%s]' % (tickerId, price, canAutoExecute)

            file.write('Last[%s,%s,%s]' % (tickerId, price, canAutoExecute))

        elif (field == 1):

            print 'Bid[%s,%s,%s]' % (tickerId, price, canAutoExecute)

            file.write('Last[%s,%s,%s]' % (tickerId, price, canAutoExecute))

        elif (field == 2):

            print 'Ask[%s,%s,%s]' % (tickerId, price, canAutoExecute)

            file.write('Last[%s,%s,%s]' % (tickerId, price, canAutoExecute))

当我运行此程序时,收到以下消息:

id:对关闭的文件执行I/O操作

连接关闭

我不确定的是时机。我想打开文件一次,然后让它保持开放,而所有这些价格来了,并得到书面。你知道我需要做什么吗


Tags: self脚本fielddef价格pricefilewrite
1条回答
网友
1楼 · 发布于 2024-06-01 00:31:55

变更单

with open('log_me.txt','w') as file:

    def tickPrice(self, tickerId, field, price, canAutoExecute):

作为

def tickPrice(self, tickerId, field, price, canAutoExecute):
    with open('log_me.txt','w') as file:

但是您应该注意,open中的w标志将在每次调用tickPrice时重新写入您的文件。您可以通过使用将append data保存到文件的标志a来忽略此行为

相关问题 更多 >