python-以“ w”模式打开文件:IOError:[Errno 2]没有这样的文件或目录
当我尝试使用以下代码在写入模式下打开文件时:
IOError: [Errno 2] No such file or directory: 'dir/dir2/dir3/some_file.mol2'
给我以下错误:
IOError: [Errno 2] No such file or directory: 'dir/dir2/dir3/some_file.mol2'
如果文件不存在,“ w”模式应该创建文件,对吗? 那么怎么会发生这个错误呢?
lugte098 asked 2020-07-21T20:54:55Z
7个解决方案
47 votes
如果包含您要打开的文件的目录不存在,即使尝试以“ 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")
Lee answered 2020-07-21T20:56:10Z
15 votes
由于您没有“开始”斜杠,因此您的python脚本正在相对于当前工作目录(而不是文件系统根目录)查找此文件。 另请注意,指向该文件的目录必须存在!
并且:使用os.path.join组合路径的元素。
例如:os.path.join("dir", "dir2", "dir3", "myfile.ext")
ChristopheD answered 2020-07-21T20:56:39Z
7 votes
我遇到了同样的错误,但在我的情况下,原因是在Windows下,路径的长度超过了〜250个字符。
Antonio answered 2020-07-21T20:56:59Z
1 votes
在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")
MSK answered 2020-07-21T20:57:27Z
1 votes
我遇到了同样的问题,但根本原因与这里的任何人都不一样。 以为我愿意分享,以防其他人遇到同样的问题。
就我而言,我不小心将括号放在了“ 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: '//bin/python/'
这些括号将'w'与with()函数一起使用,而不是按预期的方式与open()一起使用。 我很惊讶它给出了此IO错误,这意味着open()调用存在问题,这比显然来自with()调用要难得多。
我不相信这些结果,只是再次对其进行修改以进行复制,是的,我得到了相同的错误。
当我将括号切换到正确的版本时:
with (open(os.path.join(curpath, unique_name), 'w')) as fw:
它按预期工作。
Joel Wigton answered 2020-07-21T20:58:14Z
0 votes
检查脚本是否对该目录具有写权限。 试试这个:
chmod a+w dir/dir2/dir3
请注意,这将向该目录中的每个人授予写权限。
Felix answered 2020-07-21T20:58:39Z
0 votes
如果您尝试覆盖断开的具有相同名称的文件的软链接,也会发生此错误。 在这种情况下,删除断开的软链接,您将可以写入新文件。
abruin answered 2020-07-21T20:58:59Z