FileNotFoundError is a subclass of OSError, catch that or the exception itself:
except OSError as e:
Operating System exceptions have been reworked in Python 3.3; FileNotFoundError was added, and IOError has been merged into OSError. See the PEP 3151: Reworking the OS and IO exception hierarchy section in the What's New documentation.
For more details the OS Exceptions section for more information, scroll down for a class hierarchy.
That said, your code should still just work as IOError is now an alias for OSError:
>>> IOError
<class 'OSError'>
Make sure you are placing your exception handler in the correct location. Take a close look at the traceback for the exception to make sure you didn't miss where it is actually being raised. Last but not least, you did restart your Python script, right?
Answer from Martijn Pieters on Stack OverflowFileNotFoundError is a subclass of OSError, catch that or the exception itself:
except OSError as e:
Operating System exceptions have been reworked in Python 3.3; FileNotFoundError was added, and IOError has been merged into OSError. See the PEP 3151: Reworking the OS and IO exception hierarchy section in the What's New documentation.
For more details the OS Exceptions section for more information, scroll down for a class hierarchy.
That said, your code should still just work as IOError is now an alias for OSError:
>>> IOError
<class 'OSError'>
Make sure you are placing your exception handler in the correct location. Take a close look at the traceback for the exception to make sure you didn't miss where it is actually being raised. Last but not least, you did restart your Python script, right?
Change your OSError to (IOError, OSError) that should work.
@Thomas Wagenaar
How do I fix the Python FileNotFoundError Errno 2 No such file or directory?
What does the FileNotFoundError: [Errno 2] No such file or directory error mean?
Why am I seeing a FileNotFoundError: [Errno 2] No such file or directory error?
[Solved] I am an idiot. I had a folder called KanjiDrag, and within that I had the actual source folder kanji_drag which is where the json file and the main module were. The path I was using was accessing the KanjiDrag folder, but not the kanji_drag folder, and I didn't catch the different names. This is my dumbest file IO mistake yet. Thanks for all the replies, many of which I'll still refer to later when I refine this part of my program. Upvotes for everyone!
Hi, all. I'm running into a "no such file or directory" issue in python that I can't figure out.
I'm using windows 7, and I have the file in the same directory as the program I'm running. I got this error, so then I tried using the absolute path (the file is still in the same working directory anyway) and still got the same error. I even checked with os.getcwd and os.path.abspath and copy-pasted the path exactly.
I'm not sure what's going on here. I closed every program that could possibly be running the file. Would I be getting this error if the file is still open in some elusive background program?
This is the relevant bit of code:
print(os.getcwd())
print(os.path.abspath('RainyGenki1&2.json'))
deckName = "C:\Users\myName\My Documents\LiClipse Workspace\KanjiDrag\RainyGenki1&2.json"
deck = open(deckName, 'r') #opens card deckwindows is going on.
backslashes are special characters in strings.
annoyingly windows uses them to seperate paths.
to print a backslash you need to escape it with a backslash
print("\\")
There are two things to try. We usually don't use the ...\\... approach because it isn't portable and it's really easy to forget to do it (or miss one backslash).
You can use forward slashes in Windows now, I believe:
deckName = "C:/Users/myName/My Documents/myfile.txt"
And you can compose a path with raw strings:
deckName = r"C:\Users\myName\My Documents\LiClipse Workspace\KanjiDrag\RainyGenki1&2.json"
Try those out.
Another portable approach is to use the os.path functions (doc here) that use the directory separator characters appropriate to your operating system:
import os.path
path = os.path.join(BaseDirectory, 'subdir1', 'subdir2')
will give you C:\Test\subdir1\subdir1 on windows and /Test/subdir1/subdir2 on other operating systems. Also useful is the os.path.expanduser() function.
It's always a good idea if you can't seem to open a file that you know exists to compose the complete path in a string variable which you print when the operation fails.
BaseDir = r"C:\Test"
path = os.path.join(BaseDirectory, 'subdir1', 'subdir2')
try:
fp = open(path, 'r')
except IOError:
print("IOError: for file '%s'" % path)
raise
# file opened succesfully
you may use:
import os
import json
filename = 'username.json'
username = input('What is your name ? ')
if os.path.isfile(filename ): # check if the file exist:
if os.stat(filename ).st_size == 0: # check if the file is empty
with open(filename, 'w') as fp:
json.dump([username], fp)
print('We will remember you as ' + username + ' !')
else:
with open(filename) as fp:
user_names = json.load(fp)
with open(filename, 'w') as fp:
if username in user_names :
print('Welcome back ' + username + '!')
else:
user_names.append(username)
json.dump(user_names, fp)
print('We will remember you as ' + username + ' !')
else:
with open(filename, 'w') as fp:
json.dump([username])
print('We will remember you as ' + username + ' !')
Try this:
import json
filename = 'username.json'
try:
with open(filename) as file_obj:
username = json.loads(file_obj)["name"]
except FileNotFoundError:
username = input('What is your name ? ')
with open(filename, 'w') as file_obj:
json_data = {"name": username}
json.dump(json_data, file_obj)
print('We will remember you as ' + username + ' !')
else:
print('Welcome back ' + username + '!')
If FileNotFoundError isn't there, define it:
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
Now you can catch FileNotFoundError in Python 2 since it's really IOError.
Be careful though, IOError has other meanings. In particular, any message should probably say "file could not be read" rather than "file not found."
You can use the base class exception EnvironmentError and use the 'errno' attribute to figure out which exception was raised:
from __future__ import print_function
import os
import errno
try:
open('no file of this name') # generate 'file not found error'
except EnvironmentError as e: # OSError or IOError...
print(os.strerror(e.errno))
Or just use IOError in the same way:
try:
open('/Users/test/Documents/test') # will be a permission error
except IOError as e:
print(os.strerror(e.errno))
That works on Python 2 or Python 3.
Be careful not to compare against number values directly, because they can be different on different platforms. Instead, use the named constants in Python's standard library errno module which will use the correct values for the run-time platform.
I'm getting this error, despite the file existing. My code is
file = open('./foo.json')
data = json.load(file)
file.close()
return dataThe file does exist, in the same directory. I have also tried
file = open(os.path.join(sys.path[0], "foo.json"), "r")
But I get the same error. I think this might be happening because my code is running in a docker container. Any tips?
EDIT: I was able to solve the issue. Use
print(os.listdir())
Then fix the path from there
it depends on the folder where you are running the script, not the script folder.
For get the real path to the directory where your script are, you can use it :
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
open(dir_path + '/' + 'data.json')
To solve the problem you must move the data.json file out of the the python script folder,and then run the program.
Your code is perfectly fine.
Pass in arguments:
import errno
import os
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), filename)
FileNotFoundError is a subclass of OSError, which takes several arguments. The first is an error code from the errno module (file not found is always errno.ENOENT), the second the error message (use os.strerror() to obtain this), and pass in the filename as the 3rd.
The final string representation used in a traceback is built from those arguments:
>>> print(FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), 'foobar'))
[Errno 2] No such file or directory: 'foobar'
In Python, a variable can refer to the type (class), or an object (instance of the class):
>>> x = FileNotFoundError
>>> print(type(x))
<class 'type'>
>>> x = FileNotFoundError()
>>> print(type(x))
<class 'FileNotFoundError'>
While it's possible to also throw the type FileNotFoundError, you practically always want to throw an object that has been constructed from the class. The constructor accepts the same arguments as OSError. You can pass a standard POSIX and Windows error code, but it's enough to pass an error message. (In your case the standard error message "No such file or directory" is not entirely accurate, since you also throw the error if a directory is found.)
if not os.path.isfile("nothing.txt"):
raise FileNotFoundError("nothing.txt was not found or is a directory")
Let me clarify how Python finds files:
- An absolute path is a path that starts with your computer's root directory, for example
C:\Python\scriptsif you're on Windows. - A relative path is a path that does not start with your computer's root directory, and is instead relative to something called the working directory.
If you try to do open('recentlyUpdated.yaml'), Python will see that you are passing it a relative path, so it will search for the file inside the current working directory.
To diagnose the problem:
- Ensure the file exists (and has the right file extension): use
os.listdir()to see the list of files in the current working directory. - Ensure you're in the expected directory using
os.getcwd().
(If you launch your code from an IDE, you may be in a different directory.)
You can then either:
- Call
os.chdir(dir)wherediris the directory containing the file. This will change the current working directory. Then, open the file using just its name, e.g.open("file.txt"). - Specify an absolute path to the file in your
opencall.
By the way:
- Use a raw string (
r"") if your path uses backslashes, like so:dir = r'C:\Python32'- If you don't use raw string, you have to escape every backslash:
'C:\\User\\Bob\\...' - Forward-slashes also work on Windows
'C:/Python32'and do not need to be escaped.
- If you don't use raw string, you have to escape every backslash:
Example: Let's say file.txt is found in C:\Folder.
To open it, you can do:
os.chdir(r'C:\Folder')
open('file.txt') # relative path, looks inside the current working directory
or
open(r'C:\Folder\file.txt') # absolute path
Most likely, the problem is that you're using a relative file path to open the file, but the current working directory isn't set to what you think it is.
It's a common misconception that relative paths are relative to the location of the python script, but this is untrue. Relative file paths are always relative to the current working directory, and the current working directory doesn't have to be the location of your python script.
You have three options:
Use an absolute path to open the file:
file = open(r'C:\path\to\your\file.yaml')Generate the path to the file relative to your python script:
from pathlib import Path script_location = Path(__file__).absolute().parent file_location = script_location / 'file.yaml' file = file_location.open()(See also: How do I get the path and name of the file that is currently executing?)
Change the current working directory before opening the file:
import os os.chdir(r'C:\path\to\your\file') file = open('file.yaml')
Other common mistakes that could cause a "file not found" error include:
Accidentally using escape sequences in a file path:
path = 'C:\Users\newton\file.yaml' # Incorrect! The '\n' in 'Users\newton' is a line break character!To avoid making this mistake, remember to use raw string literals for file paths:
path = r'C:\Users\newton\file.yaml' # Correct!(See also: Windows path in Python)
Forgetting that Windows doesn't display file extensions:
Since Windows doesn't display known file extensions, sometimes when you think your file is named
file.yaml, it's actually namedfile.yaml.yaml. Double-check your file's extension.
I'm learning about try-except blocks but I'm encountering this Name Error whenever I try to deal with a potential File Not Found Error. Here is my code:
try:
with open("mytext.txt", "r") as f_obj:
x = f_obj.read()
print (x)
except FileNotFoundError:
print "You don't have this file, bro"I run the script, and I get "NameError: name 'FileNotFoundError' is not defined"..Any ideas?