uploading files to file system/zipping/downloading problems

Larry Bates larry.bates at websafe.com
Mon Aug 21 11:13:34 EDT 2006


OriginalBrownster wrote:
> I am currently uploading a file from a users computer to the file
> system on my server using python, just reading the file and writing the
> binaries.
> 
>         total_data=' '
>         while True:
>             data = upload_file.file.read(8192)
>             if not data:
>                 break
>             total_data += data
>             f = open(target_file_name, 'wb')
>             f.write(total_data)
>             f.close
> 
> However when i download the file from the server it is not intact and
> it cannot be opened. It is happening with every type of file.
> 
> It seemed to be working before and now it is..maybe I goofed up and
> deleted something.
> However I can't seem to find it.
> 
> any ideas??
> 
Two problems:

First, If you start total_data with a single space (as it shows in your
posted code).  Then the output file has a space prepended to the
file's contents and that is NOT what you probably wanted.

Secondly, You are overwriting the files contents every time through
the loop.  Your open, would need to be outside the loop (above the
while) and your close should be outside the loop also. Something more
like:

        total_data=''
        f = open(target_file_name, 'wb')

        while True:
            data = upload_file.file.read(8192)
            if not data:
                break
            total_data += data
            f.write(total_data)

        f.close

You should take a look at shutil module.  It is copyfile method
that makes your code must simpler (and faster I'm sure).

do

import shutl
help(shutil.copyfile)

import shutil
shutil.copyfile(uload_file_name, target_file_name)


-Larry Bates



More information about the Python-list mailing list