Reputation: 15
I am a n00b programmer and I have a python program that reads a text file in the same folderas itself. PyCharm can't seem to find that text file. Does anyone know why?
My program:
password_file = open('passwords.txt', 'r')
print(password_file.read())
password_file.close()
PyCharm can't seem to find the text file - the error message:
C:\Users\User\AppData\Local\Programs\Python\Python38-32\python.exe C:/Users/User/PycharmProjects/password_test/password.py
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/password_test/password.py", line 1, in <module>
password_file = open('passwords.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'passwords.txt'
Process finished with exit code 1
Like I said, the python program (password.py) is located in the same folder as the text file (passwords.txt). The main reason I find this strange is because I have set a program up like this before and it worked just fine. However, when I use a full path, like so:
password_file = open('C:/Users/User/PycharmProjects/password_test/passwords.txt', 'r')
print(password_file.read())
password_file.close()
my program prints the text file just fine.
What's going on and, more importantly, how do I fix it?
Thank you in advance and have a nice night.
Upvotes: 1
Views: 2506
Reputation: 2646
File is opened relative to your working directory. It doesn't matter where your "password.py" is, it only matters where are you running your "python.exe" from. If you use command line to start it, then you should navigate into directory with that file. If you're using PyCharm - you can set "Working directory:" inside "Run/Debug Configurations" window from "Run -> Edit Configurations...".
Upvotes: 2