Reputation: 474
In PyCharm, I created folder named test, created txt file named test inside and marked folder as content root. When I added python file outside the test folder and tried to access test.txt file with open it suggested me file name. But when I tried running the code it couldn't find the file.
Traceback (most recent call last):
File "/home/elmo/PycharmProjects/TBC_PAY_API_TESTING/testing.py", line 32, in <module>
print(open("test.txt").read())
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
This is how the code and folders look like ( ingore the trash folder)
How can I fix it? The main reason I am doing this is to avoid writing full path's for accessing file.
Upvotes: 0
Views: 1529
Reputation: 5319
You are talking about two totally different things in your question. If you mark a folder as Sources root
that means the Python interpreter will be able to find the modules in that folder.
For example:
When you write an own module and you want to use it in another file the Python won't find it automatically. The PYTHONPATH
should contain the path of the folder which contains your module. And actually the Sources root
option does this!
The other thing what you have mentioned in your question is that you don't provided a correct path in your code. It is a real error. In your code, you have to provide the correct path for open
. The Pycharm
is an IDE but your (or other's) Python interpreter will use your code.
You can solve your problem in many ways.
For example:
You can hard-code the path of your txt (It is totally not recommended):
print(open("/home/elmo/PycharmProjects/TBC_PAY_API_TESTING/test/text.txt").read())
You can use relative path:
print(open("test/text.txt").read())
You can use full path based on your Python file (I recommend this solution):
import os
dir = os.path.realpath(os.path.dirname(__file__)) # Directory of your Python file
file_path = os.path.join(dir, "test", "test.txt") # Create the path of the file
print(open(file_path).read())
Upvotes: 2