以"w"打开文件模式:IOError:[Errno 2]没有这样的文件或目录 [英] open file in "w" mode: IOError: [Errno 2] No such file or directory

查看:99
本文介绍了以"w"打开文件模式:IOError:[Errno 2]没有这样的文件或目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I try to open a file in write mode with the following code:

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

The "w" mode should create the file if it doesn't exist, right? So how can this error ever occur?

推荐答案

即使包含试图打开的文件的目录不存在,您也会看到此错误以"w"模式打开文件.

You'll see this error if the directory containing the file you're trying to open does not exist, even when trying to open the file in "w" mode.

由于要使用相对路径打开文件,因此您可能对该目录的确切位置感到困惑.尝试快速打印以进行检查:

Since you're opening the file with a relative path, it's possible that you're confused about exactly what that directory is. Try putting a quick print to check:

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")

这篇关于以"w"打开文件模式:IOError:[Errno 2]没有这样的文件或目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆