[英]How do I get my code to write to the text file over a python server
Client Code: 客户代码:
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')
I get the following error: 我收到以下错误:
TypeError: write() argument must be str, not bytes
Any answers would be greatly appreciated. 任何答案将不胜感激。
two ways to do that: either open your file in binary (note the 'b'
in the file mode) and write bytes
: 有两种方法:以二进制打开文件(在文件模式下注意'b'
)并写入bytes
:
with open('received_file.txt', 'wb') as f:
f.write(data)
or decode the data to a str
before writing: 或在写入之前将数据解码为str
:
with open('received_file.txt', 'w') as f:
f.write(data.decode('utf-8'))
or use any other encoding if you are not using utf-8
. 或使用其他编码(如果您未使用utf-8
。
a side-note: in your code you have two open files called f
(the 2nd one in the else
part). 旁注:在您的代码中,您有两个打开的文件,称为f
( else
部分中的第二个文件)。 that may not be a good idea... 那可能不是一个好主意...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.