如何在 Python 中获取父目录? [英] How do I get the parent directory in Python?
本文介绍了如何在 Python 中获取父目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能告诉我如何以跨平台的方式在Python中获取路径的父目录.例如
Could someone tell me how to get the parent directory of a path in Python in a cross platform way. E.g.
C:\Program Files ---> C:\
和
C:\ ---> C:\
如果目录没有父目录,则返回目录本身.这个问题可能看起来很简单,但我无法通过 Google 挖掘它.
If the directory doesn't have a parent directory, it returns the directory itself. The question might seem simple but I couldn't dig it up through Google.
推荐答案
Python 3.4
使用 pathlib
模块.
from pathlib import Path
path = Path("/here/your/path/file.txt")
print(path.parent.absolute())
旧答案
试试这个:
Old answer
Try this:
import os
print os.path.abspath(os.path.join(yourpath, os.pardir))
其中 yourpath
是您希望父路径的路径.
where yourpath
is the path you want the parent for.
这篇关于如何在 Python 中获取父目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文