2017-01-23 51 views
0

客戶端代碼寫入文本文件:如何讓我的代碼,在蟒蛇服務器

import socket     

s = socket.socket()   
host = '127.0.0.1'   
port = 8081     

s.connect((host, port)) 
s.send("Hello server!".encode('utf-8')) 

with open('received_file.txt', 'w+') as f: 
    print('file opened') 
    while True: 
     print('receiving data...') 
     data = s.recv(1024) 
     print('data=%s' % data) 
     if not data: 
      break 
     else: 
      f = open('received_file.txt') 
      f.write(data) 

    f.close() 
print('Successfully get the file') 
s.close() 
print('connection closed') 

我得到以下錯誤:

TypeError: write() argument must be str, not bytes 

任何答案,將不勝感激。

回答

1

兩種方式做到這一點:無論是在二進制打開文件(注意在文件模式'b')和寫bytes

with open('received_file.txt', 'wb') as f: 
    f.write(data) 

或解碼數據的str寫入前:

with open('received_file.txt', 'w') as f: 
    f.write(data.decode('utf-8')) 

或使用任何其他編碼,如果你不使用utf-8

附註:在您的代碼中,您有兩個打開的文件,稱爲felse部分中的第二個文件)。這可能不是一個好主意......