No such file or Directory?
Are you saying something like: «Curses! It works on my machine?»?
Use absolute, not relative paths¶
One common reason for these kinds of errors is that your working directory settings might be different on PythonAnywhere from your own machine.
The fix is to use the full, absolute path, instead of a «relative» path. So, eg:
And not just myfile.txt.
Tip: __file__ for cross-platform scripts¶
«That’s annoying!», I hear you exclaim, «my pythonanywhere username isn’t the same as my local username. and I’m on Windows maybe, so paths arent’ the same! Relative paths are so convenient! I don’t want to run different code on my machine and on PA». A very reasonable grumble. But fear not:
code like this, based on deriving the current path from Python’s magic __file__ variable, will work both locally and on the server, both on Windows and on Linux.
Another possibility: case-sensitivity¶
One other thing that might be going on is that you’re using the wRoNG cAsINg . Casing doesn’t matter on Windows but it does on Linux (and therefore, it matters on PythonAnywhere). So, be consistent with Uppercase and lowercase!
Want to improve this page? Submit a pull request!
Copyright © 2011-2022 PythonAnywhere LLP — Terms — Privacy & Cookies
«Python» is a registered trademark of the Python Software Foundation.
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
I am trying to open the file recentlyUpdated.yaml from my Python script. But when I try using:
I get an error that says:
Why? How can I fix the problem?
8 Answers 8
- 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) where dir is the directory containing the file. Then, open the file using just its name, e.g. open("file.txt") .
- Specify an absolute path to the file in your open call.
- 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.
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\scripts if 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. You can view Python’s current working directory by calling os.getcwd() .
If you try to do open(‘sortedLists.yaml’) , Python will see that you are passing it a relative path, so it will search for the file inside the current working directory.
Calling os.chdir() will change the current working directory.
Example: Let’s say file.txt is found in C:\Folder .
To open it, you can do:

/ does not work too. So you need to use /home/user/temp/file.txt instead of
is a shorthand in a shell, not the filesystem. If you want Python to expand it, use os.path.expanduser() or pathlib.Path.expanduser() .
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:
Generate the path to the file relative to your python script:
Change the current working directory before opening the file:
Other common mistakes that could cause a «file not found» error include:
Accidentally using escape sequences in a file path:
To avoid making this mistake, remember to use raw string literals for file paths:
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 named file.yaml.yaml . Double-check your file’s extension.

The file may be existing but may have a different path. Try writing the absolute path for the file.
Try os.listdir() function to check that atleast python sees the file.
Try it like this:

Possibly, you closed the ‘file1’.
Just use ‘w’ flag, that create new file:mode is an optional string that specifies the mode in which the file is opened. It defaults to ‘r’ which means open for reading in text mode. Other common values are ‘w’ for writing (truncating the file if it already exists).

If is VSCode see the workspace. If you are in other workspace this error can rise
Understanding absolute and relative paths
The term path means exactly what it sounds like. It shows the steps that need to be taken, into and out of folders, to find a file. Each step on the path is either a folder name, the special name . (which means the current folder), or the special name .. (which means to go back/out into the parent folder).
The terms absolute and relative also have their usual English meaning. A relative path shows where something is relative to some start point; an absolute path is a location starting from the top.
Paths that start with a path separator, or a drive letter followed by a path separator (like C:/foo ) on Windows, are absolute. (On Windows there are also UNC paths, which are necessarily absolute. Most people will never have to worry about these.)
Paths that directly start with a file or folder name, or a drive letter followed directly by the file or folder name (like C:foo ) on Windows, are relative.
Understanding the "current working directory"
Relative paths are "relative to" the so-called current working directory (hereafter abbreviated CWD). At the command line, Linux and Mac use a common CWD across all drives. (The entire file system has a common "root", and may include multiple physical storage devices.) Windows is a bit different: it remembers the most recent CWD for each drive, and has separate functionality to switch between drives, restoring those old CWD values.
Each process (this includes terminal/command windows) has its own CWD. When a program is started from the command line, it will get the CWD that the terminal/command process was using. When a program is started from a GUI (by double-clicking a script, or dragging something onto the script, or dragging the script onto a Python executable) or by using an IDE, the CWD might be any number of things depending on the details.
Importantly, the CWD is not necessarily where the script is located.
The script’s CWD can be checked using os.getcwd , and modified using os.chdir . Each IDE has its own rules that control the initial CWD; check the documentation for details.
To set the CWD to the folder that contains the current script, determine that path and then set it:
Verifying the actual file name and path
There are many reasons why the path to a file might not match expectations. For example, sometimes people expect C:/foo.txt on Windows to mean "the file named foo.txt on the desktop". This is wrong. That file is actually — normally — at C:/Users/name/Desktop/foo.txt (replacing name with the current user’s username). It could instead be elsewhere, if Windows is configured to put it elsewhere. To find the path to the desktop in a portable way, see How to get Desktop location?.
It’s also common to mis-count .. s in a relative path, or inappropriately repeat a folder name in a path. Take special care when constructing a path programmatically. Finally, keep in mind that .. will have no effect while already in a root directory ( / on Linux or Mac, or a drive root on Windows).
Take even more special care when constructing a path based on user input. If the input is not sanitized, bad things could happen (e.g. allowing the user to unzip a file into a folder where it will overwrite something important, or where the user ought not be allowed to write files).
Another common gotcha is that the special
shortcut for the current user’s home directory does not work in an absolute path specified in a Python program. That part of the path must be explicitly converted to the actual path, using os.path.expanduser . See Why am I forced to os.path.expanduser in python? and os.makedirs doesn't understand "
Keep in mind that os.listdir will give only the file names, not paths. Trying to iterate over a directory listed this way will only work if that directory is the current working directory.
It’s also important to make sure of the actual file name. Windows has an option to hide file name extensions in the GUI. If you see foo.txt in a window, it could be that the file’s actual name is foo.txt.txt , or something else. You can disable this option in your settings. You can also verify the file name using the command line; dir will tell you the truth about what is in the folder. (The Linux/Mac equivalent is ls , of course; but the problem should not arise there in the first place.)
Backslashes in ordinary strings are escape sequences. This causes problems when trying to a backslash as the path separator on Windows. However, using backslashes for this is not necessary, and generally not advisable. See Windows path in Python.
При попытке прочесть файл вылетает ошибка: нет такого файла или директории. Питон версии 3.5.2. Как заставить нормально работать?
Why you are not using relative path: Что в переводе используйте относительные пути. Я думаю беда где-то в этом.
Настоятельно рекомендую использовать Unix систему.
- Вконтакте

- Вконтакте


- Вконтакте
) Вам тут предложили выполнить команду cd (скопировав copy/paste наименование директории их Вашей же программы) и потом dir. Работает?
2) Проблема только с этим файлом или со всеми?
3) У Вас, часом питоновский скрипт в песочнице (sandbox) не запускается?
4) Часом где-нибудь русской буквы, совпадающей по написанию с английской нет в пути?
[Solved] IOError errno 2 no such file or directory

Like any programming language, an error in python occurs when a given code fails to follow the syntax rules. When a code does not follow the syntax, python cannot recognize that segment of code, so it throws an error. Errors can be of different types, such as runtime error, syntax error, logical error, etc. IOError errno 2 no such file or directory is one such type of error. Let us first understand each individual term of the error.
Note : Starting from Python 3.3, IOError is an aliases of OSError
What is IOError?
An IOError is thrown when an input-output operation fails in the program. The common input-output operations are opening a file or a directory, executing a print statement, etc. IOError is inherited from the EnvironmentError. The syntax of IOError is:
IOError : [Error number] ‘Reason why the error occurred’: ‘name of the file because of which the error occurred’
Examples of IOError are :
- Unable to execute the open() statement because either the filename is incorrect or the file is not present in the specified location.
- Unable to execute the print() statements because either the disk is full or the file cannot be found
- The permission to access the particular file is not given.
What is errno2 no such file or directory?
The ‘errorno 2 no such file or directory‘ is thrown when you are trying to access a file that is not present in the particular file path or its name has been changed.
This error is raised either by ‘FileNotFoundError’ or by ‘IOError’. The ‘FileNotFoundError’ raises ‘errorno 2 no such file or directory‘ when using the os library to read a given file or a directory, and that operation fails.
The ‘IOError’ raises ‘errorno 2 no such file or directory‘ when trying to access a file that does not exist in the given location using the open() function.
Handling ‘IOError [errorno 2] no such file or directory’
‘IOError errorno 2 no such file or directory‘ occurs mainly while we are handling the open() function for opening a file. Therefore, we will look at several solutions to solve the above error.
We will check if a file exists , raise exceptions, solve the error occurring while installing ‘requirements.txt,’ etc.
Checking if the file exists beforehand
If a file or a directory does not exist, it will show ‘IOError [errorno 2] no such file or directory’ while opening it. Let us take an example of opening a file named ‘filename.txt’.
The given file does not exist and we shall see what happens if we try to execute it.
Since the above text file does not exist, it will throw the IOError.
To avoid the above error from being thrown, we will use several methods which will first check if the file exists or not. It will execute the open() function only if the file exists.
We have two modules containing functions for checking if a file exists.
- OS Module
- Pathlib Module
Using the OS Module
In the os module, there are three functions which can be used:
- os.path.isfile()
- os.path.isdir()
- os.path.exists()
To solve the IOError, we can use either of the above function in a condition statement. We will pass the pathname of the file as an argument to the above functions.
If the file or the directory exists, the function shall return True else False. Bypassing either of the above functions as the conditional statement ensures that python will open a file only if it exists, thus preventing an error from occurring.
We will use os.path.isfile() when we want to check if a file exists or not, os.path.isdir() to check if a directory exists or not and os.path.exists() to check if a path exists or not.
Since we want to check for a file, we can use either the os.path.isfile() function or os.path.exists() function. We shall apply the function to the above example.
First, we have imported the os module. Then we have a variable named ‘path_name‘ which stores the path for the file.
We passed the path_name as an argument to the os.path.isfile() function. If the os.path.isfile() function returns a true value. Then it will print “File exists” and execute the other file operations.
If the file does not exist, then it will print the second statement in the else condition. Unlike the previous case, here, it will not throw an error and print the message.
Similarly, we can also use os.path.exists() function.
Using the pathlib module
The pathlib module contains three functions – pathlib.Path.exists(), pathlib.Path.is_dir() and pathlib.Path.is_file().
We will use pathlib.Path.is_file() in this example. Just like the os module, we will use the function in an if conditional statement.
It will execute the open() function only if the file exists. Thus it will not throw an error.
Since the file does not exist, the output is :
Using try – except block
We can also use exception handling for avoiding ‘IOError Errno 2 No Such File Or Directory’. In the try block, we will try to execute the open() function.
If the file is present, it will execute the open() function and all the other file operations mentioned in the try block. But, if the file cannot be found, it will throw an IOError exception and execute the except block.
Here, it will execute the except block because ‘filename.txt’ does not exist. Instead of throwing an error, it will print the IOError.
We can also print a user defined message in the except block.
The output will be:
IOError errno 2 no such file or directory in requirements.txt
Requirements.txt is a file containing all the dependencies in a project and their version details.
Basically, it contains the details of all the packages in python needed to run the project. We use the pip install command to install the requirements.txt file. But it shows the ‘IOError errno 2 no such file or directory’ error.
The thrown error is:
To solve the above error, we use the pip freeze command. When we use pip freeze, the output will contain the package along with its version.
The output will be in a configuration that we will use with the pip install command.
Now, we will try to execute the pip install command again. It will no longer throw errors and all the packages will be installed successfully.
Opening file in ‘w+’ mode
While trying to open a text file, the default mode will be read mode. In that case, it will throw the ‘IOError Errno 2 No Such File Or Directory’ error.
The output is:
To solve the error, we can open the file in ‘w+’ mode. This will open the file in both – reading and writing mode. If the file does not exist, it will create a new file, and if the file exists, it will overwrite the contents of the file. This way, it will not throw an error.
The output is:
Apart from all the above methods, there are some ways to ensure that the IOError does not occur. You have to ensure that you are giving the absolute path as the path name and not simply the name of the file.
Also, see to that there are no escape sequences in the path name of this file.
Also, Read
FAQ’s on IOError Errno 2 No Such File Or Directory
Both the errors occur when you are trying to access a file that is not present in the particular file path, or its name has been changed. The difference between the two is that FileNotFoundError is a type of OSError, whereas IOError is a type of Environment Error.
This sums up everything about IOError Errno 2 No Such File Or Directory. If you have any questions, do let us know in the comments below.