1

所以,

我一直在编写一个下载器,每次运行它时,它都会说:

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()
4

3 回答 3

10

问题是 python 没有意识到您正在使用 %USERNAME% 来引用环境变量,因此 python 从字面上解释它。你必须告诉python它是一个环境变量,通过这样做:

代替

f = open('c:\\users\\%USERNAME%\\AppData\\Roaming\\.minecraft\\mods\\CreeperCraft.zip', 'wb+')

import os
f = open(os.path.expandvars('c:\\users\\%USERNAME%\\AppData\\Roaming\\.minecraft\\mods\\CreeperCraft.zip'), 'wb+')
于 2012-08-07T15:05:43.317 回答
8

问题是%USERNAME%默认情况下不展开。os.path.expandvars在您的路径上使用。

fp = path.expandvars(r'c:\\users\%USERNAME%\AppData\Roaming\.minecraft\mods\CreeperCraft.zip')
于 2012-08-07T15:06:56.453 回答
0

我的方法是在 Windows 资源管理器中使 AppData 文件夹“取消隐藏”,然后像使用其他文件一样通过 Python 正常访问它,即 Python 无法在 cmd 行上看到 AppData,直到您“取消隐藏”它,然后您可以将其作为普通目录访问。

于 2014-04-22T13:02:14.973 回答