使用 os.path.join() 构建绝对路径 [英] constructing absolute path with os.path.join()

查看:40
本文介绍了使用 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(或 C:etcinit.d on w32),我只想从元素 etcinit.d 构造它(在 w32 上,我可能还需要一个磁盘 ID,如C:)

edit0: for instance there is a directory on the root of my filesystem /etc/init.d (or C:etcinit.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: %s" % (os.path.join('etc', 'init.d'),)
 MYPATH: etc/init.d

添加一个虚拟的第一个元素(例如 '')没有任何帮助:

Adding a dummy first-element (e.g. '') doesn't help anything:

 print("MYPATH: %s" % (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: %s" % (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: %s" % (os.path.abspath(os.path.join('etc', 'init.d')),)
 MYPATH: /home/foo/etc/init.d

那么,标准的跨平台root"方式是什么?路径?

So, what is the standard cross-platform way to "root" a path?

 root = ??? # <--
 print("MYPATH: %s" % (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屋!

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