处理相对路径
当我运行以下脚本时:
c:\Program Files\foo\bar\scripy.py
我该如何引用目录 'foo'
呢?
有没有什么方便的方法可以使用相对路径?
我之前用过字符串模块,但一定有更好的方法(我在 os.path
中找不到)。
4 个回答
1
我最近开始使用这个unipath
库,而不是使用os.path
。它对路径的面向对象表示方式简单多了:
from unipath import Path
original = Path(__file__) # .absolute() # r'c:\Program Files\foo\bar\scripy.py'
target = original.parent.parent
print target # Path(u'c:\\Program Files\\foo')
Path
是str
的一个子类,所以你可以用它来和标准的文件系统函数一起使用,但它也为很多函数提供了替代方案:
print target.isdir() # True
numbers_dir = target.child('numbers')
print numbers_dir.exists() # False
numbers_dir.mkdir()
print numbers_dir.exists() # True
for n in range(10):
file_path = numbers_dir.child('%s.txt' % (n,))
file_path.write_file("Hello world %s!\n" % (n,), 'wt')
4
os.path
模块提供了很多处理路径的功能。在大多数操作系统中,使用..
可以表示“上一级目录”,所以如果你想要访问外面的目录,可以这样做:
import os
import os.path
current_dir = os.getcwd() # find the current directory
print current_dir # c:\Program Files\foo\bar\scripy.py
parent = os.path.join(current_dir, "..") # construct a path to its parent
print parent # c:\Program Files\foo\bar\..
normal_parent = os.path.normpath(parent) # "normalize" the path
print normal_parent # c:\Program Files\foo
# or on one line:
print os.path.normpath(os.path.join(os.getcwd(), ".."))
1
os.path.dirname(path)
这个函数会返回对路径参数进行分割后得到的后半部分。简单来说,就是返回这个路径所在的目录。你可能需要做两次这个操作,但这可能是最好的方法。
关于path
函数的Python文档: