以"w"模式打开文件:IOError:[Errno 2]没有这样的文件或目录

lug*_*098 46 python file-io

当我尝试使用以下代码在写入模式下打开文件时:

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"模式应该创建文件,对吧?那么这个错误怎么会发生呢?

Lee*_*Lee 50

如果包含您尝试打开的文件的目录不存在,即使尝试以"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")
Run Code Online (Sandbox Code Playgroud)


Chr*_*heD 16

由于您没有"起始"斜杠,因此您的python脚本正在查找相对于当前工作目录的此文件(而不是文件系统的根目录).另请注意,导致该文件的目录必须存在!

并且:使用os.path.join组合路径的元素.

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


Ant*_*nio 7

我有同样的错误,但在我的情况下,原因是在Windows下,路径长度超过〜250个字符。

  • 我还发现它是 Windows 路径长度问题。 (2认同)