Transferring files using sockets

brueckd at tbye.com brueckd at tbye.com
Wed Apr 10 13:35:38 EDT 2002


On Wed, 10 Apr 2002, Skip Montanaro wrote:

>
>     IC> I am trying to transfer a file using the socket module, but I'm not
>     IC> sure how to do this. Should I split the file into little(1KB)
>     IC> packages and then transfer them, or is there a possibility to send
>     IC> the whole file?
>
> It should be possible to just execute
>
>     sock.send(open("somefile").read())
>
> if sock is a connected stream socket.  You might want to break it down in
> chunks though, either to conserve local memory or provide transit feedback:
>
>     f = open("somefile")
>     while 1:
>         data = f.read(8192)
>         if not data:
>             break
>         sock.send(data)
>         sys.stderr.write(".")
>         sys.stderr.flush()
>     sys.stderr.write("\n")

Also, 'send' doesn't necessarily send the whole chunk of data; as a return
value it gives you the number of bytes actually sent. Python 2.2 and later
sockets have a sendall method you can use instead.

-Dave






More information about the Python-list mailing list