2010-03-08 215 views
31

当我尝试在模式用下面的代码打开一个文件:打开文件:IO错误:[错误2]没有这样的文件或目录

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

回答

33

你会看到这个错误,如果包含目录你试图打开不存在的文件,试图打开“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") 
1

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

chmod a+w dir/dir2/dir3 

请注意,这将给该目录上的每个人写入权限。

+2

-1;这不是OP错误的可能原因。如果你没有对目录的写权限,Python会给你'IOError:[Errno 13]权限被拒绝:'testdir/foo',而不是'没有这样的文件或目录'错误。 – 2016-01-06 18:52:29

14

由于您没有“开始”斜杠,因此您的python脚本正在查找与当前工作目录相关的文件(而不是文件系统的根目录)。另请注意,文件前的目录必须存在!并且:使用os.path.join来组合路径的元素。

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

1

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

+0

我也发现它是Windows路径长度问题。 – blueray 2018-03-08 10:25:24

0

在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") 
加入这个
相关问题