pythonfilenotfounderror

FileNotFoundError: [Errno 2] No such file or directory, while the file does exist and it's in the same folder


I'm coding something and I need to open a .txt file on the code. I have both the code and the text file in the same folder, yet I still get this error: FileNotFoundError: [Errno 2] No such file or directory: 'dis_rules.txt'. The code I wrote was directly taken from a different thread on this page, and obviouly the file name written in the code is identical. Here's the folder with both files on it.

Here's the code I've used too:

fp = open(r"dis_rules.txt", 'r')
print(fp.read())

What could be wrong on this? Thank you for your help!


Solution

  • Thanks to the comments you guys posted I got to solve the issue. As you all said, the problem was that the current directory of the file was different to the folder's directory. To solve this, I had to use the os.chdir() method to change the currently directory to the folder's directory, this way:

    import os
    
    path = "C:\\Users\\utente\\Desktop\\_rules2"
    os.chdir(path)
    

    After that I just added the code I posted on the question and it worked just fine. Thank you everyone for your help!