打开文件:IO错误:[错误2]没有这样的文件或目录
问题描述:
当我尝试在写模式用下面的代码打开一个文件:打开文件: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”模式,应该创建文件?那么这个错误怎么会发生呢?
答
你会看到这个错误,如果包含目录你试图打开不存在的文件,试图打开“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")
答
检查脚本是否具有该目录的写入权限。试试这个:
chmod a+w dir/dir2/dir3
请注意,这将给该目录上的每个人写入权限。
答
由于您没有“开始”斜杠,因此您的python脚本正在查找与当前工作目录相关的文件(而不是文件系统的根目录)。另请注意,文件前的目录必须存在!并且:使用os.path.join来组合路径的元素。
例如为:os.path.join("dir", "dir2", "dir3", "myfile.ext")
答
在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")
加入这个
-1;这不是OP错误的可能原因。如果你没有对目录的写权限,Python会给你'IOError:[Errno 13]权限被拒绝:'testdir/foo',而不是'没有这样的文件或目录'错误。 – 2016-01-06 18:52:29