0

In R and R Studio I use relative paths to load data files. This makes the code runnable on anybody else's computer, and hence makes my research reproducible.

To do the same in Python, I have tried using os.path.dirname(__file__) to get the path of my script, but the interpreter does not recognize __file__.

2
  • You mean paths relative to the file being executed? Python has no inherent problem with relative paths. Commented Nov 11, 2024 at 0:02
  • "but the interpreter does not recognize __file__" what does that mean exactly? What exactly are you doing? How are you running Python? Commented Nov 11, 2024 at 0:03

2 Answers 2

1

In python you can also use relative paths for accessing files and directories. The only thing to consider is you cannot go back further from the root of the package you are running when using import.

For accessing files and datasets you still can do whatever you want (read/write/etc) from wherever you want as long as you have permissions to do so, but for importing them, you cannot.

If you want to import files from other places, you have 2 options:

  1. Create separated modules and import them,
  2. Use symlink (ln in unix-base systems) inside your project.
0

I solved it. It's very simple really. One just has to configure Spyder in Tools -> Preferences -> Working Directory -> At startup the working directory is: The Project… Then it behaves exactly like R Studio and one can load data files into dataframes by using relative paths (relative to the working directory).

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.