没有这样的文件或目录,怪异或什么?
我一直在编码下载,我每次运行它时,它说:
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()
问题是Python没有意识到你正在使用%USERNAME%指一个环境变量,所以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+')
另外,使用[os.path.join](http://docs.python.org/library/os.path.html#os.path.join)加入路径。 – 2012-08-07 15:07:14
感谢expandvars小费。 – Lanaru 2012-08-07 15:08:47
很高兴能帮到你:-) – 2012-08-07 15:11:39
的问题是,%USERNAME%
默认情况下不扩大。在你的路径上使用os.path.expandvars
。
fp = path.expandvars(r'c:\\users\%USERNAME%\AppData\Roaming\.minecraft\mods\CreeperCraft.zip')
我的方法是使AppData文件夹“取消隐藏”在Windows资源管理器,然后只需访问它通常是通过Python作为你将与其他文件,即Python不能看到应用程序数据的CMD线,直到你“取消隐藏”它,那么你可以作为一个普通的目录来访问它。
确保该目录存在,如果没有,请使用[makedirs](http://docs.python.org/library/os.html#os.makedirs)来制作它。 – 2012-08-07 15:05:51
Python的'open'函数是否真的在Windows上扩展环境变量? ('c:\\ users \%USERNAME%\ AppData \ Roaming \ .minecraft \ mods \ CreeperCraft.zip') – Dirk 2012-08-07 15:06:22
您可能更适合使用'%APPDATA'而不是'C:\ Users \%USERNAME \ AppData \ Roaming'。另外,使用原始字符串('r'c:\ ...')或正斜杠来避免在路径中加双反斜杠。 – lvc 2012-08-07 15:13:02