有人能告诉我如何在Python中跨平台获取路径的父目录吗?如。
C:\Program Files ---> C:\
and
C:\ ---> C:\
如果目录没有父目录,则返回目录本身。这个问题似乎很简单,但我无法从谷歌中找到它。
有人能告诉我如何在Python中跨平台获取路径的父目录吗?如。
C:\Program Files ---> C:\
and
C:\ ---> C:\
如果目录没有父目录,则返回目录本身。这个问题似乎很简单,但我无法从谷歌中找到它。
当前回答
Pathlib方法(Python 3.4+)
from pathlib import Path
Path('C:\Program Files').parent
# Returns a Pathlib object
传统方法
import os.path
os.path.dirname('C:\Program Files')
# Returns a string
我应该用哪种方法?
如果出现以下情况,请使用传统方法:
如果要使用Pathlib对象,您会担心现有代码生成错误。(因为Pathlib对象不能与字符串连接。) 您的Python版本低于3.4。 你需要一个字符串,你收到了一个字符串。例如,你有一个表示文件路径的字符串,你想要得到父目录,这样你就可以把它放在一个JSON字符串中。转换为Pathlib对象然后再转换回来是很愚蠢的。
如果以上都不适用,请使用Pathlib。
什么是Pathlib?
如果你不知道Pathlib是什么,Pathlib模块是一个很棒的模块,它可以让你更容易地处理文件。大多数(如果不是全部的话)内建的处理文件的Python模块将同时接受Pathlib对象和字符串。我在下面突出了几个来自Pathlib文档的例子,这些例子展示了你可以用Pathlib做的一些漂亮的事情。
在目录树中导航:
>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')
查询路径属性。
>>> q.exists()
True
>>> q.is_dir()
False
其他回答
获取父目录路径并创建新目录(名称为new_dir)
获取父目录路径
os.path.abspath('..')
os.pardir
示例1
import os
print os.makedirs(os.path.join(os.path.dirname(__file__), os.pardir, 'new_dir'))
示例2
import os
print os.makedirs(os.path.join(os.path.dirname(__file__), os.path.abspath('..'), 'new_dir'))
Pathlib方法(Python 3.4+)
from pathlib import Path
Path('C:\Program Files').parent
# Returns a Pathlib object
传统方法
import os.path
os.path.dirname('C:\Program Files')
# Returns a string
我应该用哪种方法?
如果出现以下情况,请使用传统方法:
如果要使用Pathlib对象,您会担心现有代码生成错误。(因为Pathlib对象不能与字符串连接。) 您的Python版本低于3.4。 你需要一个字符串,你收到了一个字符串。例如,你有一个表示文件路径的字符串,你想要得到父目录,这样你就可以把它放在一个JSON字符串中。转换为Pathlib对象然后再转换回来是很愚蠢的。
如果以上都不适用,请使用Pathlib。
什么是Pathlib?
如果你不知道Pathlib是什么,Pathlib模块是一个很棒的模块,它可以让你更容易地处理文件。大多数(如果不是全部的话)内建的处理文件的Python模块将同时接受Pathlib对象和字符串。我在下面突出了几个来自Pathlib文档的例子,这些例子展示了你可以用Pathlib做的一些漂亮的事情。
在目录树中导航:
>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')
查询路径属性。
>>> q.exists()
True
>>> q.is_dir()
False
import os
def parent_directory():
# Create a relative path to the parent of the current working directory
relative_parent = os.path.join(os.getcwd(), "..") # .. means parent directory
# Return the absolute path of the parent directory
return os.path.abspath(relative_parent)
print(parent_directory())
print os.path.abspath(os.path.join(os.getcwd(), os.path.pardir))
您可以使用它来获取py文件当前位置的父目录。
import os
p = os.path.abspath('..')
C:\Program Files——> C:\\\
C:\\\