代码之家  ›  专栏  ›  技术社区  ›  Alex

为什么我的os.rename不工作?

  •  1
  • Alex  · 技术社区  · 15 年前

    if os.path.isfile(fullPath):
        print 'fmf exists'
        print fullPath
        print newFilePath
        os.rename(fullPath,newFilePath)
    

    我得到以下错误:

    fmf exists
    (correct fullPath)
    (correct newFilePath, ie. destination)
    Traceback (most recent call last):
      File "whatever.py", line 374, in ?
        os.rename(fullPath,newFilePath)
    OSError: [Errno 2] No such file or directory
    

    自从我 如果fullPath中的文件存在,我对这个错误感到困惑。当然,newFilePath不存在,因为那样会很愚蠢。有什么提示吗?

    谢谢! 亚历克斯

    *他们不都是吗?

    4 回复  |  直到 15 年前
        1
  •  1
  •   Ayman Hourieh    15 年前

    如果尝试复制到不存在的目录,仍然可以得到异常。

        2
  •  1
  •   inspectorG4dget Dillon Benson    15 年前

    我看不到你代码的全部内部工作原理,所以这是我的两分钱:

    您的newFilePath可能包含一个不存在的目录。如果是这样,那么根据您的操作系统,您的程序将无法在不存在的目录中创建文件。那可能是你的错误。

    希望这有帮助

        3
  •  0
  •   Nathan Johnson    12 年前

        4
  •  0
  •   Chris Martin    10 年前

    当我的新文件名包含正斜杠时,我也遇到了同样的错误,正斜杠与Unix和Linux中的目录分隔符相混淆。例如,将文件重命名为“4/27/2015.txt”会导致一个不存在的目录,并导致“没有这样的文件或目录”。您可以通过用任何其他可接受的字符替换正斜杠来解决此问题。

    推荐文章