python:获取目录两个级别 [英] python: get directory two levels up
问题描述
好吧...我不知道模块x
在哪里,但是我知道我需要把目录的路径上移两个级别.
Ok...I dont know where module x
is, but I know that I need to get the path to the directory two levels up.
因此,有没有一种更优雅的方法:
So, is there a more elegant way to do:
import os
two_up = os.path.dirname(os.path.dirname(__file__))
欢迎使用适用于Python 2和3的解决方案!
Solutions for both Python 2 and 3 are welcome!
推荐答案
您可以使用 pathlib
.不幸的是,这仅在Python 3.4的stdlib中可用.如果您使用的是旧版本,则必须在此处处从PyPI安装副本.使用pip
应该很容易做到.
You can use pathlib
. Unfortunately this is only available in the stdlib for Python 3.4. If you have an older version you'll have to install a copy from PyPI here. This should be easy to do using pip
.
from pathlib import Path
p = Path(__file__).parents[1]
print(p)
# /absolute/path/to/two/levels/up
这使用parents
序列,该序列提供对父目录的访问并选择第二个目录.
This uses the parents
sequence which provides access to the parent directories and chooses the 2nd one up.
请注意,在这种情况下,p
将是某种形式的Path
对象,具有自己的方法.如果您需要路径为字符串,则可以在其上调用str
.
Note that p
in this case will be some form of Path
object, with their own methods. If you need the paths as string then you can call str
on them.
这篇关于python:获取目录两个级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!