For some reason my code is having trouble opening a simple file:
This is the code:
file1 = open('recentlyUpdated.yaml')
And the error is:
IOError: [Errno 2] No such file or directory: 'recentlyUpdated.yaml'
open()
the full path to the file and none of it seems to work.os.listdir()
to see the list of files in the current working directoryos.getcwd()
(if you launch your code from an IDE, you may well be in a different directory)os.chdir(dir)
, dir
being the folder where the file is
located, then open the file with just its name like you were doing.open
call.dir = r'C:\Python32'
'C:\\User\\Bob\\...'
'C:/Python32'
and do not need to be escaped.Let me clarify how Python finds files:
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:
os.chdir(r'C:\Folder')
open('file.txt') #relative path, looks inside the current working directory
or
open(r'C:\Folder\file.txt') #full path