画像のようなバイナリファイルを読み書きするには、みんなのPythonで出ている例では駄目なのだろうか。urllib2と組み合わせたら、うまく動作しない。urllib2でイメージを取得すると、BASE64文字列でなく、バイナリを返してきた。保存できなかった。ググってみたら、同じことで煮詰まった人がMLにいた
wrote: > hi, i want to automate some tasks of gathering photos from web, i tried
> urllib/urllib2, both ended up without much success (saved gifs with
> only a border, nothing else)..
>
> the code i used was:
>
> >>> data = urllib2.urlopen(
"http://aspn.activestate.com/ASPN/img/komodo_aspn_other.gif")
> >>> #was looking through cookbook, so i used that as a sample image
> >>> data = data.read()
> >>> file = open("f:/test.gif", "w")Since you appear to want to write binary data, you should use 'wb', not
'w', as the "mode".
Alex
どうやらファイルを開くときにバイナリーモードなるモノが存在するようだ。
追記:
urllib2はContent-Encoding: gzipを解決してくれない。なのでread()で返される文字列がすべてバイナリになることがある。画像が保存できなかった原因にgzipの解凍処理抜けがあるようだ