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

在“w”模式下打开文件:ioerror:[errno 2]没有此类文件或目录

  •  36
  • lugte098  · 技术社区  · 15 年前

    当我试图打开一个文件时 具有以下代码的模式:

    packetFile = open("%s/%s/%s/%s.mol2" % ("dir", "dir2", "dir3", "some_file"), "w")

    给出以下错误:

    IOError: [Errno 2] No such file or directory: 'dir/dir2/dir3/some_file.mol2'

    如果文件不存在,“w”模式应该创建文件,对吗?那么这个错误怎么会发生呢?

    6 回复  |  直到 7 年前
        1
  •  39
  •   Mark Amery Harley Holcombe    9 年前

    如果 目录 即使试图以“w”模式打开文件,也不存在包含您试图打开的文件的文件。

    因为您是用相对路径打开文件的,所以您可能对该目录的具体内容感到困惑。尝试快速打印以检查:

    import os
    
    curpath = os.path.abspath(os.curdir)
    packet_file = "%s/%s/%s/%s.mol2" % ("dir", "dir2", "dir3", "some_file")
    print "Current path is: %s" % (curpath)
    print "Trying to open: %s" % (os.path.join(curpath, packet_file))
    
    packetFile = open(packet_file, "w")
    
        2
  •  15
  •   ChristopheD    15 年前

    由于没有“开始”斜杠,所以python脚本将查找相对于当前工作目录(而不是文件系统根目录)的文件。还要注意,指向文件的目录必须存在!

    和:使用 os.path.join 结合路径的元素。

    例如。: os.path.join("dir", "dir2", "dir3", "myfile.ext")

        3
  •  4
  •   Antonio    8 年前

    我也有同样的错误,但在我的例子中,原因是,在Windows下,路径长度超过了大约250个字符。

        4
  •  0
  •   Felix    15 年前

    检查脚本是否对该目录具有写权限。试试这个:

    chmod a+w dir/dir2/dir3
    

    请注意,这将授予该目录上的所有人写权限。

        5
  •  0
  •   Stephen Rauch Afsar Ali    7 年前

    在Windows环境中也发生了类似的问题。解决方法是在绝对路径中添加“c”。 我的目标是在用户桌面上保存一些文件

    file_path = os.path.join(os.environ["HOMEPATH"], os.path.join("Desktop", 
        "log_file.log_%s_%s" %(
        strftime("%Y_%m_%d", localtime()), "number_1")))
    

    然后我试图打开这个目录来保存 例如

    file_ref = open(file_path, "w")
    

    我添加这个是为了运行

    file_ref = open(("C:\\"+file_path), "w")
    
        6
  •  0
  •   abruin    7 年前

    如果试图覆盖到同名文件的断开软链接,也会发生此错误。在这种情况下,删除断开的软链接,您将能够写入新文件。