Newbie

Mikael Olofsson mikael at isy.liu.se
Thu Nov 16 17:02:29 CET 2000


On 16-Nov-00 Andreas Palsson wrote:
 > ###
 >  print "Content-Type: image/jpeg"
 >  print
 >  f=open('myjpeg.jpg', 'rb')
 >  buffer = f.read()
 >  print buffer
 >  f.close()
 > ###
 >  
 >  But if the picture is 8-10mb in size, it becomes quite hard on the server.
 >  So instead I would like to have a loop in which I read 32k, then outputs
 >  32k until I've reached the end of the file.

>From the Python Library Reference:

    2.1.7.9 File Objects

    ...

    Files have the following methods:

    ...

    read ([size]) 
         Read at most size bytes from the file (less if the read hits 
         EOF before obtaining size bytes). If the size argument is 
         negative or omitted, read all data until EOF is reached. The 
         bytes are returned as a string object. An empty string is 
         returned when EOF is encountered immediately. (For certain 
         files, like ttys, it makes sense to continue reading after an 
         EOF is hit.) Note that this method may call the underlying C 
         function fread() more than once in an effort to acquire as
         close to size bytes as possible. 

So something like the following should do the trick.

    import sys
    print "Content-Type: image/jpeg\n"
    f=open('myjpeg.jpg', 'rb')
    buffer='x'
    while buffer:
        buffer = f.read(2^15)
        sys.stdout.write(buffer)
    f.close()

Good luck.

/Mikael

-----------------------------------------------------------------------
E-Mail:  Mikael Olofsson <mikael at isy.liu.se>
WWW:     http://www.dtr.isy.liu.se/dtr/staff/mikael               
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
Date:    16-Nov-00
Time:    16:53:16

         /"\
         \ /     ASCII Ribbon Campaign
          X      Against HTML Mail
         / \

This message was sent by XF-Mail.
-----------------------------------------------------------------------




More information about the Python-list mailing list