[英]Python Downloading Zip Files Damaged
So, I've been trying to make a simple downloader that downloads my zip file. 因此,我一直在尝试制作一个简单的下载器来下载我的zip文件。
Code looks like this: 代码如下:
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()
And the problem is, it downloads the file to the correct path, but when I open the file, its damaged, only 1 picture appears and when you click on it, it says File Damaged
. 问题是,它会将文件下载到正确的路径,但是当我打开文件时,文件损坏了,只有1张图片出现,并且当您单击它时,
File Damaged
。
Please help. 请帮忙。
f = open('c:\CreeperCraft.zip', 'wb+')
You are using "w+" as flag, Python opens the file in text mode: 您使用“ w +”作为标志,Python以文本模式打开文件:
Python on Windows makes a distinction between text and binary files;
Windows上的Python区分文本文件和二进制文件。 the end-of-line characters in text files are automatically altered slightly when data is read or written.
当读取或写入数据时,文本文件中的行尾字符会自动更改。 This behind-the-scenes modification to file data is fine for ASCII text files, but it'll corrupt binary data like that in JPEG or EXE files.
对于ASCII文本文件来说,对文件数据进行这种幕后修改是可以的,但它会破坏JPEG或EXE文件中的二进制数据。
http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files
Also, note that you should escape the backslash or use raw strings, therefore use open('c:\\\\CreeperCraft.zip', 'wb+')
. 另外,请注意,您应该转义反斜杠或使用原始字符串,因此请使用
open('c:\\\\CreeperCraft.zip', 'wb+')
。
I also would recommend that you do not copy raw byte strings by hand, but use shutil.copyfileobj
- it makes your code more compact and easier to understand. 我还建议您不要手动复制原始字节字符串,而应使用
shutil.copyfileobj
它使您的代码更紧凑,更易于理解。 I also like to use the with
statement that automatically cleans up resources (ie that closes files: 我还喜欢使用
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)
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.