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?
os.listdir()to see the list of files in the current working directory.os.getcwd().(If you launch your code from an IDE, you may be in a different directory.)
os.chdir(dir)wherediris the directory containing the file. Then, open the file using just its name, e.g.open("file.txt").opencall.r"") if your path uses backslashes, likeso:
dir = r'C:\Python32''C:\\User\\Bob\\...''C:/Python32'and do not need to be escaped.Let me clarify how Python finds files:
C:\Python\scriptsif you’re on Windows.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.txtis found inC:\Folder.To open it, you can do:
or