用os.path.join()构造绝对路径 [英] constructing absolute path with os.path.join()
问题描述
我想在python中构造一个绝对路径,而与此同时却对诸如路径分隔符之类的东西一无所知.
I'd like to construct an absolute path in python, while at the same time staying fairly oblivious of things like path-separator.
edit0 :例如,在我的文件系统/etc/init.d
(或w32上的C:\etc\init.d
)的根目录中有一个目录,我只想从元素etc
和init.d
(在w32上,我可能还需要一个磁盘ID,例如C:
)
edit0: for instance there is a directory on the root of my filesystem /etc/init.d
(or C:\etc\init.d
on w32), and I want to construct this only from the elements etc
and init.d
(on w32, I probably also need a disk-ID, like C:
)
为了不必担心路径分隔符,os.join.path()
显然是首选工具.但这似乎只会创建相对路径:
In order to not having to worry about path-separators, os.join.path()
is obviously the tool of choice. But it seems that this will only ever create relative paths:
print "MYPATH:", os.path.join('etc', 'init.d')
MYPATH: etc/init.d
添加虚拟的第一元素(例如''
)无济于事:
Adding a dummy first-element (e.g. ''
) doesn't help anything:
print "MYPATH:", os.path.join('', 'etc', 'init.d')
MYPATH: etc/init.d
将第一个元素设为绝对显然会有所帮助,但这种做法破坏了使用os.path.join()
Making the first element absolute obviously helps, but this kind of defeats the idea of using os.path.join()
print "MYPATH:", os.path.join('/etc', 'init.d')
MYPATH: /etc/init.d
edit1 :使用os.path.abspath()
只会尝试将相对路径转换为绝对路径.
例如考虑在工作目录/home/foo
中运行以下命令:
edit1: using os.path.abspath()
will only try to convert a relative path into an absolute path.
e.g. consider running the following in the working directory /home/foo
:
print "MYPATH:", os.path.abspath(os.path.join('etc', 'init.d'))
MYPATH: /home/foo/etc/init.d
那么,扎根"路径的标准跨平台方法是什么?
So, what is the standard cross-platform way to "root" a path?
root = ??? # <--
print "MYPATH:", os.path.join(root, 'etc', 'init.d')
MYPATH: /etc/init.d
edit2 :问题的实质可以归结为:由于/etc/init.d
中的前导斜线使该路径成为绝对路径,是否有办法以编程方式构造该前导斜线?
(我不想假设斜杠表示绝对路径)
edit2: the question really boils down to: since the leading slash in /etc/init.d
makes this path an absolute path, is there a way to construct this leading slash programmatically?
(I do not want to make assumptions that a leading slash indicates an absolute path)
推荐答案
所以我想到的解决方案是,通过将给定文件放在根目录下来构造文件系统的根目录:
so the solution i came up with, is to construct the root of the filesystem by following a given file to it's root:
def getRoot(file=None):
if file is None:
file='.'
me=os.path.abspath(file)
drive,path=os.path.splitdrive(me)
while 1:
path,folder=os.path.split(path)
if not folder:
break
return drive+path
os.path.join(getRoot(), 'etc', 'init.d')
这篇关于用os.path.join()构造绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!