["python","file-io"]
open file in "w" mode: IOError: [Errno 2] No such file or directory

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") I get the following error: IOError: [Errno 2] No such file or directory: 'dir/dir2/dir3/some_file.mol2' The w mode should create the file if it doesn't exist, right? So how can this error ever occur?
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")