Relative Address In Python
Referring to the question here Relative paths in Python. I have similar problem to that. My project structure: proj | |--config | |--ENV | |--folder1 | |--UI | |
Solution 1:
My Project
some_file.py
Resources
bg.png
music.mp3
Folder
another_file.py
If you want to access your resources from some_file.py, the relative path would be ./Resources/...
but if you want to use resources from another_file.py you would do ../Resources/...
.
So in your case if you want to access ENV file from test1.py, its relative location would be ./config/ENV
, but if you want to access it from test2.py, its relative location would be ../../config/ENV
.
Remember ../
means going up one level and ./
means the same level.
Edits:
Here you've the fixed path config/ENV
. Passing that fixed path in relative_path()
gives you the relative path address.
# proj
# config
# ENV
#
# folder1
# config
# some_other_file.txt
#
# UI
# test2.py
#
# test1.py
import os
def relative_path(path):
# Get the parent directory of the
# file that you need the relative
# path for.
my_dir = path.split('/')[0]
# Recursively match the directory
# in the given path. if the match
# not found go up one level.
def match_dir(c_path):
c_path = os.path.split(c_path)[0]
if my_dir in os.listdir(c_path) and (
os.path.isfile(
os.path.join(c_path, path)
)
):
# this whole if-block can be omitted
# if the folder you're trying to access
# is on the same level, this just prepends
# with './'. I added this just for
# aesthetic reason.
if os.path.basename(__file__) in os.listdir(c_path):
return './' + path
return path
return "../" + match_dir(c_path)
return match_dir(
os.path.realpath(__file__)
)
# Getting relative path from test2.py
print(relative_path("config/ENV"))
print(relative_path("config/some_other_file.txt"))
# Try running this from test1.py
print(relative_path("config/ENV")) # './config/ENV'
This isn't very much optimized. Just a general idea.
Post a Comment for "Relative Address In Python"