如何解析python中的相对路径? [英] How to resolve relative paths in python?

查看:77
本文介绍了如何解析python中的相对路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的目录结构

projectfolder/fold1/fold2/fold3/script.py

现在我给 script.py 一个路径作为

now I'm giving script.py a path as commandline argument of a file which is there in

fold1/fold_temp/myfile.txt

所以基本上我希望能够以这种方式给出路径

So basically I want to be able to give path in this way

../../fold_temp/myfile.txt 

>>python somepath/pythonfile.py -input ../../fold_temp/myfile.txt

这里的问题是我可能会得到完整路径或相对路径,所以我应该能够决定并基于此我应该能够创建绝对路径.

Here problem is that I might be given full path or relative path so I should be able to decide and based on that I should be able to create absolute path.

我已经了解了与路径相关的函数.

I already have knowledge of functions related to path.

问题 1

问题2

参考问题给出了部分答案,但我不知道如何使用其中提供的函数构建完整路径.

Reference questions are giving partial answer but I don't know how to build full path using the functions provided in them.

推荐答案

import os
dir = os.path.dirname(__file__)
path = raw_input()
if os.path.isabs(path):
    print "input path is absolute"
else:
    path = os.path.join(dir, path)
    print "absolute path is %s" % path

使用os.path.isabs判断输入路径是绝对路径还是相对路径,如果是相对路径,则使用os.path.join转换为绝对路径

Use os.path.isabs to judge if input path is absolute or relative, if it is relative, then use os.path.join to convert it to absolute

这篇关于如何解析python中的相对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆