代码之家  ›  专栏  ›  技术社区  ›  Richard Knop

没有这样的文件或目录错误

  •  3
  • Richard Knop  · 技术社区  · 14 年前

    这是我得到的错误:

    Traceback (most recent call last):
      File "E:\stuff\module.py", line 91, in <module>
        f = open('E:/stuff/log.txt')
    IOError: [Errno 2] No such file or directory: 'E:/stuff/log.txt'
    

    这是我的代码:

    f = open('E:/stuff/log.txt')
    

    这个 E:/stuff/log.txt 文件存在。我可以在Windows资源管理器中导航并打开它,为什么不能打开它?

    编辑:

    C:\Documents and Settings\Administrator>dir e:\stuff
     Volume in drive E has no label.
     Volume Serial Number is 5660-4957
    
     Directory of e:\stuff
    
    23. 10. 2010  09:26    <DIR>          .
    23. 10. 2010  09:26    <DIR>          ..
    19. 10. 2010  20:07               385 index.py
    23. 10. 2010  16:12             1 954 module.py
    22. 10. 2010  19:16             8 335 backprop.py
    19. 10. 2010  20:54             1 307 backprop-input.gif
    19. 10. 2010  01:48               310 HelloWorld.kpf
    23. 10. 2010  15:47                 0 log.txt.txt
                   6 File(s)         12 291 bytes
                   2 Dir(s)   8 795 586 560 bytes free
    
    
    
    C:\Documents and Settings\Administrator>dir e:\
     Volume in drive E has no label.
     Volume Serial Number is 5660-4957
    
     Directory of e:\
    
    16. 10. 2010  13:32    <DIR>          development-tools
    23. 10. 2010  09:26    <DIR>          stuff
                   0 File(s)              0 bytes
                   2 Dir(s)   8 795 586 560 bytes free
    

    我在cmd中运行python脚本,如下所示:

    python E:\stuff\module.py
    
    6 回复  |  直到 14 年前
        1
  •  11
  •   Tim Čas    14 年前

    首先,从上面看,Windows支持/很好。

    其次:

    我建议您禁用这个-请参阅文件夹选项,应该有一个选项“隐藏已知文件类型的扩展名”(或类似)。

        2
  •  3
  •   brady    14 年前

    查看“dir”输出中的这一行:

    23. 10. 2010  15:47                 0 log.txt.txt
    

    您要查找的文件名为“log.txt.txt”,而不是“log.txt”。当人们将Windows文件管理器设置为不显示已知的文件扩展名,然后试图添加或修改扩展名时,我看到了这种情况。我建议其他人关掉这种行为。您可以在“查看”->“我相信的文件夹选项”下执行此操作。

        3
  •  1
  •   tutuDajuju    14 年前

        4
  •  1
  •   Rawheiser    14 年前

    因为它是windows,而且反斜杠是转义字符,所以必须加倍反斜杠才能转义。尝试

    e:\\stuff\\log.txt
    
        5
  •  1
  •   mouad    14 年前

    很长一段时间我没有使用windows,但如果我记得很好,windows在系统路径中使用反斜杠,那么您应该这样做:

    import os
    
    file_name = os.path.join("e:\\stuff", "log.txt")
    
    f = open(file_name)
    

    而不是:

    f = open('E:/stuff/log.txt')
    

    windows中没有/在路径中。

        6
  •  1
  •   ghostdog74    14 年前

    os.path.join()

    root="E:\\"
    mylog = os.path.join(root,"stuff","log.txt") # or log.txt.txt as seen in your dir output
    f = open(mylog)
    ...
    f.close()