当我尝试使用以下代码以 write 模式打开文件时:
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 - 以 "w"模式打开文件 : IOError: [Errno 2] No such file or directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2401628/