0

I am writing a really simple webserver, based on BaseHTTPServer. What is weirding me out right now (I'm a python starter) is that a .png file that python knows to exist, is not read correctly; instead, a weird 5-byte string wending with "PNG" is read. All other files, like html, js, etc, are read and sent correctly.

Without further ado, my code excerpt, within the do_GET method:

localfilepath = curdir + sep + self.path
f = open(localfilepath)

fileContent = f.read()
fileType = os.path.splitext(localfilepath)[1]

print "isfile(%s): %s" % (self.path, str(os.path.isfile(localfilepath)))
if( len(fileContent) > 10 ):
    print "read %s file with length %s" % (fileType, str(len(fileContent)))
else:
    print "!read %s file: (length: %s, content: %s)" % (fileType, str(len(fileContent)), fileContent)

the log reads:

GET received; path: /AdaptrisSurvey/images/btn1_hover.png
127.0.0.1 - - [27/Sep/2014 19:18:03] "GET /AdaptrisSurvey/images/btn1_hover.png HTTP/1.1" 200 -
isfile(/AdaptrisSurvey/images/btn1_hover.png): True
!read .png file: (length: 5, content: ëPNG
)

(the closing bracket at the end follows a newline, but I couldn't figure out how to do that in here without a paragraph vertical indent.)

Since it works with other files, the btn1_hover.png file exists and is a real image, displayable in my standard image viewer, I am out of ideas for this.

tshepang
  • 12,111
  • 21
  • 91
  • 136
simlei
  • 155
  • 2
  • 12

2 Answers2

2

You need to open the file in binary mode:

f = open(localfilepath, "rb") 

Otherwise the reading stops as soon as it hits the SUB character that's part of the PNG header.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

in case you really want the file size of a binary file, instead of the length - perhaps see this question which refers to python docs -

os.path.getsize(path) #Return the size, in bytes, of path. Raise os.error if the file does not exist or is inaccessible.
Community
  • 1
  • 1
fluidmotion
  • 121
  • 3