Search code examples
pythonfilefile-iopathfile-not-found

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:

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?


Solution

  • 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.

    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:

    • 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. This will change the current working directory. Then, open the file using just its name, e.g. open("file.txt").
    • Specify an absolute path to the file in your open call.

    By the way:

    • Use a raw string (r"") if your path uses backslashes, like so: dir = r'C:\Python32'
      • 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.

    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