【问题标题】:Python Downloading Zip Files DamagedPython 下载 Zip 文件损坏
【发布时间】:2012-08-07 14:17:19
【问题描述】:

所以,我一直在尝试制作一个简单的下载器来下载我的 zip 文件。

代码如下:

import urllib2
import os
import shutil

url = "https://dl.dropbox.com/u/29251693/CreeperCraft.zip"

file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open('c:\CreeperCraft.zip', 'w+')
meta = u.info()

file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)

file_size_dl = 0
block_sz = 8192
while True:
    buffer = u.read(block_sz)
    if not buffer:
        break

    file_size_dl += len(buffer)
    f.write(buffer)
    status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
    status = status + chr(8)*(len(status)+1)
    print status,

f.close()

问题是,它将文件下载到正确的路径,但是当我打开文件时,它已损坏,只出现一张图片,当你点击它时,它显示File Damaged

请帮忙。

【问题讨论】:

    标签: python download urllib2


    【解决方案1】:
    f = open('c:\CreeperCraft.zip', 'wb+')
    

    【讨论】:

    • 没错。 Zip 文件是二进制文件,而不是文本文件。太糟糕了,打开文件的默认模式不是二进制的。
    • 我遇到了同样的问题,并认为这是由我的 Content-Type 或 Accept 标头引起的。我不知道(直到我读到这个答案)我的文件“打开”行没有按照需要对我的文件进行编码。
    • 太棒了,为我工作。我使用过 wb,最初代码运行良好(奇怪),但有一天它停止工作。那时将其更改为 wb+ 使其再次工作。
    【解决方案2】:

    您使用“w+”作为标志,Python 以 text 模式打开文件:

    Windows 上的 Python 区分文本文件和二进制文件; 文本文件中的行尾字符会自动更改 读取或写入数据时稍微。这个幕后 修改文件数据对于 ASCII 文本文件来说很好,但它会 损坏的二进制数据,例如 JPEG 或 EXE 文件。

    http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files

    另外,请注意您应该转义反斜杠或使用原始字符串,因此请使用open('c:\\CreeperCraft.zip', 'wb+')

    我还建议您不要手动复制原始字节字符串,而是使用shutil.copyfileobj - 它使您的代码更紧凑且更易于理解。我也喜欢使用自动清理资源的with 语句(即关闭文件:

    import urllib2, shutil
    
    url = "https://dl.dropbox.com/u/29251693/CreeperCraft.zip"
    with urllib2.urlopen(url) as source, open('c:\CreeperCraft.zip', 'w+b') as target:
      shutil.copyfileobj(source, target)
    

    【讨论】:

    • wb+ 修复了它,谢谢!,但我不明白你给我的其他代码......但无论如何,它有效!
    【解决方案3】:
    import posixpath
    import sys
    import urlparse
    import urllib
    
    url = "https://dl.dropbox.com/u/29251693/CreeperCraft.zip"
    filename = posixpath.basename(urlparse.urlsplit(url).path)
    def print_download_status(block_count, block_size, total_size):
        sys.stderr.write('\r%10s bytes of %s' % (block_count*block_size, total_size))
    filename, headers = urllib.urlretrieve(url, filename, print_download_status)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多