【问题标题】:No such file or directory, Weird Or What?没有这样的文件或目录,奇怪还是什么?
【发布时间】: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:\...') 或正斜杠以避免在路径中使用双反斜杠。

标签: python download urllib2


【解决方案1】:

问题在于 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+')

【讨论】:

  • 另外,使用os.path.join 加入路径。
  • 感谢 expandvars 提示。
【解决方案2】:

问题是%USERNAME%默认没有展开。在你的路径上使用os.path.expandvars

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2012-10-30
      • 1970-01-01
      • 2021-08-29
      • 2011-06-22
      • 2020-04-02
      • 2013-11-23
      • 1970-01-01
      • 2013-02-17
      • 2017-02-14
      相关资源
      最近更新 更多