I'm currently experiencing problems accessing files inside my python project depending on where I call the program from. I can't seem to find an appropriate answer using the search bar.
I have a project with the following structure:
PycharmProjects
└──myproject
| ├── mypackage
| │ ├── mytextfile.txt
| │ ├── __init__.py
| │ ├── __main__.py
| │ └── test.py
where I have designated mypackage as the source directory in my ide. This project will be packaged and published as a command line interface on PyPi
If I run the test file directly in my ide, it can successfully access the text file mytextfile.txt
However when I try to run the program through the terminal from my home directory as follows:
$ PycharmProjects/myproject/mypackage/test.py
it throws an error that it cannot find the file.
Currently, my reference to the text file is simple:
file = open("mytextfile.txt")
texttoprint = file.read()
file.close()
print(texttoprint)
The obvious "easy way" method would be to use the absolute file path from the root directory. This would obviously be not good and make everything less portable.
I see that there's a bunch of workarounds either involving using pathlib or adding things to paths.
I'm not certain why that is necessary though. Shouldn't a relative path from my source directory (which is mypackage currently) be all that's required?
Either way, while there may be 10's of solutions, what is the most typical. What is the "default" solution here. I guess what I'm saying is, I could find a hacky workaround, but I'm looking for what is considered the best practices here. Also if you can explain why just using a relative path from the source directory doesn't work (or even what marking a directory as source in my ide even does) that would be appreciated.
Thank you