Reputation: 2102
I am trying to open the file recentlyUpdated.yaml
from my Python script. But when I try using:
open('recentlyUpdated.yaml')
I get an error that says:
IOError: [Errno 2] No such file or directory: 'recentlyUpdated.yaml'
Why? How can I fix the problem?
Upvotes: 137
Views: 892732
Reputation: 1112
In my case it works. I was consuming json resides in rest_api dir in my project dir.
then I changed from this
f = open('rest_api/contacts0.json')
to
f = open('../rest_api/contacts0.json')
After adding ../ it was able to read file.
Upvotes: 0
Reputation: 9721
Let me clarify how Python finds files:
C:\Python\scripts
if you're on Windows.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:
os.listdir()
to see the list of files in the current working directory.os.getcwd()
.You can then either:
os.chdir(dir)
where dir
is 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")
.open
call.By the way:
r""
) if your path uses backslashes, like
so: dir = r'C:\Python32'
'C:\\User\\Bob\\...'
'C:/Python32'
and do not need to be escaped.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
Upvotes: 170
Reputation: 173
This worked for me, it shall work for you too.
#get current working directory
os.getcwd()
#trim till directory you want the resource till and get 0th from split
os.getcwd().split(dir_in_str)[0]
#list files and dirs inside dir
os.listdir(dir_in_str)
#append environment independent path seperator
path = path + f'{os.path.sep}'
#search if string is present or endswith in path
if str in path:
Happy Coding.. ;)
Upvotes: 0
Reputation: 31801
One (out of many) possible failure scenario:
os.scandir()
, os.listdir()
etc and then tried to call .stat()
on a broken symlink then the stat()
call will be attempted against the non-existent symlink target, rather than the symlink itself.By default .stat()
is called with .stat(*, follow_symlinks=True)
; use .stat(follow_symlinks=False)
to prevent following (broken) symlinks.
Upvotes: 0
Reputation: 3051
I was getting this error because it was non-obvious to me if the folder was being created or not because, in theory, a function called in the code should've done that.
import os
file_path = input('Input file path')
dir_path = os.path.dirname(file_path)
os.makedirs(dir_path, exist_ok=True)
with open(file_path) as file:
file.write("Written!")
In OP's case, he's only reading the file so it should exist in the path he provided. It might be common that we forget the w
flag for the open function (e.g. open('/path/to/file', 'w')
) and end up getting this error.
Upvotes: 2
Reputation: 61643
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.
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:
os.chdir(os.path.dirname(os.path.abspath(__file__)))
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 "~" in my path.
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 How should I write a Windows path in a Python string literal?.
When trying to create a new file using a file mode like w
, the path to the new file still needs to exist - i.e., all the intervening folders. See for example Trying to use open(filename, 'w' ) gives IOError: [Errno 2] No such file or directory if directory doesn't exist. Also keep in mind that the new file name has to be valid. In particular, it will not work to try to insert a date in MM/DD/YYYY
format into the file name, because the /
s will be treated as path separators.
Upvotes: 3
Reputation: 1102
(for Pycharm)
You may receive this error when changing the folder name because this setting isn't updated. To fix this error within Pycharm, select "Edit Configurations" (Top right of the window next to the Run button).
Then change both the script path (just in case you haven't already) and the working directory folder.
Upvotes: 1
Reputation: 19
If you are using IDE like VScode, make sure you have opened the IDE from the same directory where you have kept the file you want to access.
For example, if you want to access file.txt which is inside the Document, try opening the IDE from Document by right clicking in the directory and clicking "Open with "
Upvotes: 0
Reputation: 57
Check the path that has been mentioned, if it's absolute or relative.
If its something like-->/folder/subfolder/file
-->Computer will search for folder in root directory.
If its something like--> ./folder/subfolder/file
--> Computer will search for folder in current working directory.
Upvotes: 0
Reputation: 1565
If is VSCode see the workspace. If you are in other workspace this error can rise
Upvotes: 4
Reputation:
Possibly, you closed the 'file1'.
Just use 'w' flag, that create new file:
file1 = open('recentlyUpdated.yaml', 'w')
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)...
(see also https://docs.python.org/3/library/functions.html?highlight=open#open)
Upvotes: 3
Reputation: 43296
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 named file.yaml.yaml
. Double-check your file's extension.
Upvotes: 38
Reputation: 6555
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:
file1 = open(r'Drive:\Dir\recentlyUpdated.yaml')
Upvotes: 7