• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home » Resolved: How to tell python to use same directory for file

Resolved: How to tell python to use same directory for file

0
By Isaac Tonny on 15/03/2023 Issue
Share
Facebook Twitter LinkedIn

In this post, we will see how to resolve How to tell python to use same directory for file

Question:

I need this python project to be useable for multiple users after downloading it from git, but I’m having a problem generalizing paths. I have it set to use absolute paths in my version, but that will break for others, and if I’m using a file in the same directory as the module, python can’t find it if I use the relative path (i.e., with open('foo.txt') as f).
I settled on a text file called properties.txt in the project directory, and a module that reads it into a dict. Right now it just has one line, MAIN_DIR=/my/home/directory. The problem is circular though. I can’t use a relative path to read that text file either.
I’m confident this solution is overengineered. There’s got to be a way to get around that, or to get around the problem with relative paths in the first place?

Best Answer:

There are a few different approaches, depending on your needs and constraints.
One option is to use some “standard” location. For instance, ~/.config/myprog/foo.conf is a standardized way to locate per-user configuration files.
Another option is to have an environment variable, that your user must set. Perhaps with fallback to a “default” path of some sort (like above).
Another option, for something like a script, is to use something like cd "$(dirname "$0")"/.. — that’s Bash script, but you get the idea. In Python you’d use sys.argv[0]. This makes the current working directory the one in which the script is located. You can use relative paths from then onward.
The question mentioned in your comments has a good general overview: https://stackoverflow.com/a/58941536/567650
It depends a bit on how fancy your build/packaging setup is. If you’re just sending a file or three, then the above “change the current directory” approach is common and would probably work okay, but would fall under the “Bad way #1:” heading, in the other answer I linked.

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com

python
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How do I navigate a table without any easily accessible distinctions?

27/03/2023

Resolved: Can a pod make itself unavailable temporarily in kubernetes?

27/03/2023

Resolved: How to plot logistic probability for custom generalized additive model (GAM) plot?

27/03/2023

Comments are closed.

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.