用Python从服务器接收数据

2024-06-16 18:10:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python从客户机到服务器接收一些字节。所以我从客户端发送了一些字符串:OLA,135和A

服务器的代码行是:

while True:
    # Receive the data one byte at a time
    data = connection.recv(1)
    file = open("test.txt", "w")
    file.write(data)
    file.close()
    sys.stdout.write(data)

我想把客户端发送的字符串写在一个txt文件中。但是当我收到服务器中的所有字符串后,我打开了创建的txt文件,却什么都没有。怎么了?你知道吗


Tags: 文件字符串代码服务器txttrue客户端data
1条回答
网友
1楼 · 发布于 2024-06-16 18:10:35

在python中,用"w"打开文件会删除上一个文件。你知道吗

'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending;

所以用“a”来保存现有的数据。你知道吗

while True:
    # Receive the data one byte at a time
    data = connection.recv(1)
    file = open("test.txt", "a") # change 'w' to 'a'
    file.write(data)
    file.close()
    sys.stdout.write(data)

引用:https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

相关问题 更多 >