2014-09-27 71 views
0

我正在写一个非常简单的基于BaseHTTPServer的网络服务器。 什么是我现在(我是一个Python启动器)我是出了一个.png文件,知道python知道存在,不正确读取;取而代之的是读取一个奇怪的5字节字符串,用“PNG”修补。 所有其他文件,如html,js等,都会被正确读取并发送。file.read不返回文件(.png)的内容,但奇怪的5字节的东西

事不宜迟,我的代码摘录,所述do_GET方法中:

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) 

日志读取:

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 
) 

(末尾右括号如下换行符,但我不能”不知道如何在这里没有一个段落垂直缩进。)

因为它与其他文件一起工作,btn1_hover.png文件存在,并且是一个真实的图像,可以显示在我的标准rd图片浏览器,我对此没有想法。

回答

2

你需要以二进制方式打开文件:

f = open(localfilepath, "rb") 

否则读数,因为它击中了SUB性格是这样的PNG header的部分就停止。

1

如果你真的想要一个二进制文件的文件大小,而不是长度 - perhaps see this question这是指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.