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