Olivier Giniaux
Olivier Giniaux

Reputation: 950

Having a relative path in a module relative to the file calling the module

Let's say I have the current file structure :

modules\script.py :

import sys
sys.path.append("..\\")
from modules.module import module
[...]

main.py :

import sys
from modules.module import module
[...]

modules\module.py :

[...]
fileToRead="somefile.txt"

The problem is :

I don't want to use an absolute path as I want my app folder to be movable. I thought of a path relative to the root folder, but I don't know if it's a clean solution and I don't want to pollute all my scripts with redondant stuff.

Is there a clean way to deal with this ?

Upvotes: 4

Views: 1474

Answers (1)

martineau
martineau

Reputation: 123463

I'm not sure what all you're doing, but since somefile.txt is in the same folder as module.py, you could make the path to it relative to the module by using its predefined __file__ attribute:

import os
fileToRead = os.path.join(os.path.dirname(__file__), "somefile.txt")

Upvotes: 5

Related Questions