3

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!

Markiiuz
  • 71
  • 1
  • 1
  • 7
  • 1
    What is the [current directory](https://stackoverflow.com/questions/5137497/find-the-current-directory-and-files-directory) at the time of read? – PM 77-1 May 31 '22 at 20:57
  • 2
    https://stackoverflow.com/questions/72440639/attempting-to-read-file-in-same-directory-as-python-file-but-getting-filenotfoun/72440741#72440741 – danielhoherd May 31 '22 at 21:03
  • The current directory is indeed a different one to the folder, thank you for pointing it out. But how do I fix that? – Markiiuz May 31 '22 at 21:27
  • you have to search for the answer yourself on google depending how you are running python (like a certain bar in your IDE or cd in the cmd, etc), please read the [before you ask](https://stackoverflow.com/help/how-to-ask) and make sure you do your own research before asking. – Ahmed AEK May 31 '22 at 21:34
  • I have done my research before asking but since I'm new to Python and programming overall I might not know where to look. If I had found the answer when I did my research I wouldn't have asked here. I'm still trying though – Markiiuz May 31 '22 at 21:46

2 Answers2

4

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!

Markiiuz
  • 71
  • 1
  • 1
  • 7
0

I'm relatively new to python, and i've never seen this method of opening a text file... Try like this:

with open('dis_rules.txt','r') as f:
    print(f.readlines())

Also, not sure you need to use an r-string... Tell me if that helps!

Jogvi
  • 77
  • 1
  • 7