0

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

Derek1st
  • 63
  • 6
  • 1
    Relative file paths are resolved using the current working directory, not the location of the script. I would use an absolute path, but one *constructed* from a known (possibly configurable) base directory. – chepner Feb 25 '22 at 15:57
  • @JonSG thank you for pointing that out, I accidentally cropped out that part. I'll edit the main post but i'll also comment it here: file = open("mytextfile.txt") – Derek1st Feb 25 '22 at 16:04
  • 1
    Check out `pathlib.Path(__file__)` to construct a path relative to the current script. – JonSG Feb 25 '22 at 16:08
  • So in this case, \_\_file\_\_ is the name of THIS file right? So if my python file and my text file are in the same directory, wouldn't \_\_file\_\_ give me the name of my python file and not the name of the text file I'm trying to reach? Unless i'm misunderstanding. thank you a lot btw. I'm more trying to understand this well than I am trying to fix a specific issue – Derek1st Feb 25 '22 at 16:10
  • Try `print(pathlib.Path(__file__).parent.joinpath("file.txt"))` – JonSG Feb 25 '22 at 16:37

0 Answers0