2012-08-07 213 views
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() 
+1

確保該目錄存在,如果沒有,請使用[makedirs](http://docs.python.org/library/os.html#os.makedirs)來製作它。 – 2012-08-07 15:05:51

+4

Python的'open'函數是否真的在Windows上擴展環境變量? ('c:\\ users \%USERNAME%\ AppData \ Roaming \ .minecraft \ mods \ CreeperCraft.zip') – Dirk 2012-08-07 15:06:22

+0

您可能更適合使用'%APPDATA'而不是'C:\ Users \%USERNAME \ AppData \ Roaming'。另外,使用原始字符串('r'c:\ ...')或正斜槓來避免在路徑中加雙反斜槓。 – lvc 2012-08-07 15:13:02

回答

10

問題是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+') 
+1

另外,使用[os.path.join](http://docs.python.org/library/os.path.html#os.path.join)加入路徑。 – 2012-08-07 15:07:14

+0

感謝expandvars小費。 – Lanaru 2012-08-07 15:08:47

+0

很高興能幫到你:-) – 2012-08-07 15:11:39

8

的問題是,%USERNAME%默認情況下不擴大。在你的路徑上使用os.path.expandvars

fp = path.expandvars(r'c:\\users\%USERNAME%\AppData\Roaming\.minecraft\mods\CreeperCraft.zip') 
0

我的方法是使AppData文件夾「取消隱藏」在Windows資源管理器,然後只需訪問它通常是通過Python作爲你將與其他文件,即Python不能看到應用程序數據的CMD線,直到你「取消隱藏」它,那麼你可以作爲一個普通的目錄來訪問它。

相關問題