Python请求:下载的图像文件二进制文件与原始文件不同?

时间:2016-03-09 11:02:01

标签: python python-requests

我正在使用Python请求从Web保存图像文件。但是,保存的文件与原始文件有点二进制,有点大。它仍然是一个有效的jpg文件,但是乱七八糟。

以下是代码:

import requests
import shutil
import os

if __name__ == "__main__":

image_url = 'http://www.123.com/image.jpg'
filename = 'out.jpg'
username = 'myusername'
password = 'mypasword'
path = os.path.join('c:/', filename )

r = requests.get(image_url, auth=(username, password), stream=True)
if r.status_code == 200:
    with open(path, 'w') as f:
        r.raw.decode_content = False
        shutil.copyfileobj(r.raw, f)

print 'The End'

我做错了什么?

1 个答案:

答案 0 :(得分:4)

<?php // Get the PHP helper library from twilio.com/docs/php/install require_once('/twilio-php-master/Services/Twilio.php'); // Loads the library // Your Account Sid and Auth Token from twilio.com/user/account $sid = ""; $token = ""; $client = new Services_Twilio($sid, $token); // Loop over the list of numbers and echo a property for each one foreach ($client->account->incoming_phone_numbers as $number) { echo "<select>" . $number->phone_number . "</select>"; }

应该是:

open(path, 'w')

open(path, 'wb')用于“二进制”。这将确保Python不会尝试转换字符编码和换行符,并且完全按字节逐字节读取或写入所有内容。

另见the open() documentation