在Python中发送文件

-3 投票
1 回答
3905 浏览
提问于 2025-04-28 13:03

我在网上到处找关于如何在Python中发送文件的资料,结果100%都失败了,没人能帮我。有没有程序员能帮我把文件从客户端发送到服务器,或者反过来?

我可以很简单地发送文本文件。

#!/usr/bin/python
"""
Socket Client
"""
import socket #networking library
indent = ""
server = input("server name (default is " + socket.gethostname() + "): ") or socket.gethostname()

print("connecting to server at: %s" % server)

while True:
    clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

    clientSocket.connect((server, 23000)) 



    str = input("text to send: ")

    clientSocket.send(str.encode("utf-8")) #send text as encoded bytes

    print("received: %s" % clientSocket.recv(100).decode("utf-8")) 

    clientSocket.close()

    #strRecv = clientSocket.recv(500).decode("utf-8") #receive up to 500 bytes and decode into text
    #print(strRecv)
暂无标签

1 个回答

5

非常基础的例子:

服务器接收文件:

import socket
with socket.socket() as s:
    s.bind(('',8000))
    s.listen(1)
    with s.accept()[0] as c:
        chunks = []
        while True:
            chunk = c.recv(4096)
            if not chunk: break
            chunks.append(chunk)
    with open('out.txt','wb') as f:
        f.write(b''.join(chunks))

客户端发送文件:

import socket
with socket.socket() as s:
    s.connect(('localhost',8000))
    with open('myfile.txt','rb') as f:
        s.sendall(f.read())

撰写回答