Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

file-io

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

Gives me 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?

like image 897
lugte098 Avatar asked Mar 08 '10 13:03

lugte098


People also ask

How do I fix Errno 2 No such file or directory in Python?

The Python FileNotFoundError: [Errno 2] No such file or directory error is often raised by the os library. This error tells you that you are trying to access a file or folder that does not exist. To fix this error, check that you are referring to the right file or folder in your program.

How do you handle FileNotFoundError Errno 2 No such file or directory?

The error "FileNotFoundError: [Errno 2] No such file or directory" is telling you that there is no file of that name in the working directory. So, try using the exact, or absolute path. In the above code, all of the information needed to locate the file is contained in the path string - absolute path.

Why am I getting a No such file or directory?

log No such file or directory” the problem is most likely on the client side. In most cases, this simply indicates that the file or folder specified was a top-level item selected in the backup schedule and it did not exist at the time the backup ran.

How do I fix Python error file not found?

The solution to this problem is specifying the whole file path in the code. Note: Observe, while specifying the file path, we added an r before writing the path, pd. read_csv(r"C:\.......) . It is used to convert simple strings to raw strings.


2 Answers

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") 
like image 73
Lee Avatar answered Oct 02 '22 15:10

Lee


Since you don't have a 'starting' slash, your python script is looking for this file relative to the current working directory (and not to the root of the filesystem). Also note that the directories leading up to the file must exist!

And: use os.path.join to combine elements of a path.

e.g.: os.path.join("dir", "dir2", "dir3", "myfile.ext")

like image 44
ChristopheD Avatar answered Oct 02 '22 16:10

ChristopheD