在python中发送文件

时间:2014-10-20 11:37:06

标签: python file tcp send

我已经看过网上的每一个地方如何在python中发送文件,100%是失败的,没有人可以提供帮助。是否有任何程序员可以帮助我从客户端发送文件到服务器或其他方式?

我可以非常轻松地发送txt

#!/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 个答案:

答案 0 :(得分: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())