2014-10-31 87 views
0

我有工作Python腳本,我試圖修改。該腳本獲取股票價格並在Python控制檯中打印出來。我試圖改變這個價格寫入一個文本文件。這裏是原代碼:file.write與Python接收錯誤消息connectionClosed

類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操作就關閉的文件

connectionClosed

什麼我不知道的是時機。我想打開一次文件,然後在所有這些價格出現並寫入時讓它保持打開狀態。你知道我需要做什麼嗎?

+0

考慮使用['logging'](https://docs.python.org/2/library/logging.html)模塊。 – 2014-10-31 11:59:11

回答

1

更改爲了

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: 

但你應該關心w標誌open將重新寫的tickPrice每次調用您的文件。您可以通過使用將append data歸檔的標記a來省略此行爲。

+0

謝謝!我是否需要打開文件才能寫入 - 然後再添加?或者我可以只使用'a'標誌,它會首次打開並隨後添加? – user3229570 2014-10-31 12:08:47

+1

@ user3229570是用'a'打開也會創建文件 – 2014-10-31 12:48:49