Reputation: 77
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!
Upvotes: 3
Views: 44514
Reputation: 77
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!
Upvotes: 3
Reputation: 85
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!
Upvotes: -1