Why Python on Windows can't read an image in binary mode?
I want to read a image in binary mode so that I could save it into my database, like this:
img = open("Last_Dawn.jpg")
t = img.read()
save_to_db(t)
This is working on M开发者_开发百科ac. But on Windows, what img.read() is incorrect. It's just a little out of the whole set.
So my first question is: why code above doesn't work in Windows?
And second is: is there any other way to do this?
Thanks a lot!
You need to open in binary mode:
img = open("Last_Dawn.jpg", 'rb')
You need to tell Python to open the file in binary mode:
img = open('whatever.whatever', 'rb')
See the documentation for the open function here: http://docs.python.org/library/functions.html#open
Can't say for sure but I do know that the ISO C standard doesn't distinguish between the binary and non-binary modes when calling fopen
and yet Windows does.
It's likely that the Python code just uses fopen("Last_Dawn.jpg","r")
under the covers (since it's written in C) and this is being opened in Windows in non-binary mode.
This will most likely convert line end characters (LF -> CRLF
) and possibly others.
If you yourself specify the mode as 'rb' on your open statement, that should fix it:
img = open("Last_Dawn.jpg", "rb")
open(filename, 'rb')
精彩评论