-1

I want to set relative path to folder with my executive script that will works from any machine without hardcoding absolute path to file. So far I have following:

import os
path_to_folder = os.path.realpath('.')

When I run my script from PyCharm calling print(path_to_folder) return correct path

C:\Users\Me\Desktop\Project\Script\

But if I try to call it from cmd like python3.4 C:\Users\Me\Desktop\Project\Script\my_script.py I get just

C:\Users\Me\

What is the more reliable way to set relative path?

Andersson
  • 51,635
  • 17
  • 77
  • 129

2 Answers2

1

I used to use Pathlib

# get sibling file
sib = Path(__file__).with_name(same_level_file)

# get parent
par = Path(__file__).parent

# file in sibling parent
sib2 = Path(__file__).parent.with_name(parent_folder).joinpath(file2)     
Andersson
  • 51,635
  • 17
  • 77
  • 129
Ali SAID OMAR
  • 6,404
  • 8
  • 39
  • 56
0

You can also do this without Pathlib just using the __file__ variable that Python defines every module.

In the parent script itself:

from os.path import dirname, abspath
path_to_folder = abspath(dirname(__file__))
print(path_to_folder)

Or more generally if you just want to know where a module is located, you can just do:

from os.path import dirname, abspath
import mymodule
path_to_folder = abspath(dirname(mymodule.__file__))
print(path_to_folder)
Erotemic
  • 4,806
  • 4
  • 39
  • 80