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:

    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:

    You can then either:

    By the way:

    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