2017-01-23 52 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部分中的第二个文件)。这可能不是一个好主意......