【发布时间】:2012-08-07 15:03:50
【问题描述】:
所以,
我一直在编写一个下载器,每次运行它都会显示:
Traceback (most recent call last):
File "C:\Python27\Downloader.py", line 7, in <module>
f = open('c:\\users\%USERNAME%\AppData\Roaming\.minecraft\mods\CreeperCraft.zip', 'wb+')
IOError: [Errno 2] No such file or directory: 'c:\\users\\%USERNAME%\\AppData\\Roaming\\.minecraft\\mods\\CreeperCraft.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:\\users\%USERNAME%\AppData\Roaming\.minecraft\mods\CreeperCraft.zip', 'wb+')
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()
【问题讨论】:
-
确保目录存在,如果不存在,请使用makedirs 制作。
-
Python的
open函数真的会扩展windows上的环境变量吗? (c:\\users\%USERNAME%\AppData\Roaming\.minecraft\mods\CreeperCraft.zip) -
您最好使用
%APPDATA而不是C:\Users\%USERNAME\AppData\Roaming。此外,请使用原始字符串 (r'c:\...') 或正斜杠以避免在路径中使用双反斜杠。