使用以下代码尝试以写入模式打开文件时:
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")
由于缺少“起始”斜杠,您的 Python 脚本将相对于当前工作目录(而不是文件系统根目录)查找此文件。还要注意,指向该文件的前导目录必须存在!
另外:使用 os.path.join
来组合路径元素。
例如:os.path.join("dir", "dir2", "dir3", "myfile.ext")
我遇到了同样的错误,但在我的情况下,原因是在Windows下,路径超过了大约250个字符。
检查脚本在该目录上是否具有写权限。尝试以下操作:
chmod a+w dir/dir2/dir3
IOError: [Errno 13] Permission denied: 'testdir/foo'
的错误提示,而不是 No such file or directory
的错误提示。 - Mark Amery我遇到了同样的问题,但是我的根本原因与这里任何人都不同。为了防止其他人遇到相同的问题,我想分享一下。
在我的情况下,我无意中将括号放错了位置,放在了“with”行上:
with (open(os.path.join(curpath, unique_name)), 'w') as fw:
Traceback (most recent call last):
File "./crap.py", line 60, in uniquify
with (open(os.path.join(curpath, unique_name)), 'w') as fw:
IOError: [Errno 2] No such file or directory: '/<mypath>/bin/python/<filename>'
with (open(os.path.join(curpath, unique_name), 'w')) as fw:
它按预期工作。
open()
调用中,因为它没有获取正确的参数。with
是完全没问题的,因为你只是传递了一个元组。需要明确的是:使用with
时不需要括号,因为它不是方法而是语句。当您使用多个元素的括号时,它将被解析为元组。 - RobbertC5file_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")
如果您试图用相同名称覆盖损坏的符号链接文件,也会出现此错误。在这种情况下,请删除损坏的符号链接,然后才能写入新文件。