2015-10-13 138 views
0

以下是我的程序段:蟒蛇3.4.3 f.write不工作

with open(completepathname,'wb') as f:    
    print ('file opened') 
    print(f) 
    while True: 
      print('receiving data...') 
      print('hello') 

      data = send_receive_protocol.recv_msg(conn) 
      #print('hi') 
      print(data) 
      if not data: 
       print('printing1') 
       break 

      print('printing') 
      data1=data.encode() 
      print(data1) 
      f.write(data1)#write to file 
      f.close() 

輸出正確打印到控制檯,但如果我去打開文件是空白。如果刪除該文件,然後再執行我的程序,在文件被創建,但仍是空

+4

你爲什麼'f.close()'文件? '與'將照顧這一點。 –

+2

明顯的問題是'f.close()';因爲這是一個無限循環,你可能想要* flush *來代替。使用'f.flush()'刷新OS緩衝區。 –

+0

適用於我:這個f.close()實際上應該是f.flush(),但是至少也要用f.close()來刷新緩衝區。如果我將它作爲粘貼運行,發送一串數據,然後在第二個''recv_msg()''中阻塞,然後我看到(現在關閉的)文件中的數據。 –

回答

0

下面的代碼片段按預期工作:

with open('test.txt', 'wb') as f:    
    while True: 
      data = 'test-data' 

      if not data: 
       break 

      data1 = data.encode('hex') 
      f.write(data1) 
      f.flush() 

你應該注意不要.close()一個類似文件的對象,然後繼續嘗試寫入它。如果您需要確保輸出立即寫入,請使用.flush()