Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

python - How can I turn an absolute path into a relative path within a function?

I'm currently facing the problem that I'm working with different files. Within some of those files are other files - absolute files - I do not want to change them all to relative path since then I'll run into another problem. So my question is whether I can indicate a relative path within a function with e.g. adding two dots. So this is the code snipped:

    if not all(np.array(skills_dict['snames']) == df_cube['img_path'].values)

So 'img_path' is the absolute path and I would like to make it relative for this function, something quirky like

    df_cube['..'+'img_path'].values

Maybe someone could help me with that. Highly appreciated! Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can do something like this. It will return the relative path of absolute_path. You can replace that with whatever absolute path you need to.

import os

def get_rel_path(absolute_path):
    """
    Gets the relative path of absolute_path
    """
    return os.path.dirname(absolute_path)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...