如何获取文件的父目录? [英] How do I get a file's parent directory?

查看:52
本文介绍了如何获取文件的父目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个文件路径,c:\xxx\abc\xyz\fileName.jpg,我怎样才能获得文件的父文件夹?在这个例子中,我正在寻找 xyz.访问文件的目录数量可能会有所不同.

解决方案

使用 os.path.dirname 获取目录路径.如果你只想要目录的名字,你可以使用 os.path.basename 从中提取基本名称:

<预><代码>>>>路径 = r'c:\xxx\abc\xyz\fileName.jpg'>>>导入操作系统>>>os.path.dirname(路径)'c:\\xxx\\abc\\xyz'>>>os.path.basename(os.path.dirname(path))'xyz'

Given a path to a file, c:\xxx\abc\xyz\fileName.jpg, how can I get the file's parent folder? In this example, I'm looking for xyz. The number of directories to get to the file may vary.

解决方案

Use os.path.dirname to get the directory path. If you only want the name of the directory, you can use os.path.basename to extract the base name from it:

>>> path = r'c:\xxx\abc\xyz\fileName.jpg'
>>> import os
>>> os.path.dirname(path)
'c:\\xxx\\abc\\xyz'
>>> os.path.basename(os.path.dirname(path))
'xyz'

这篇关于如何获取文件的父目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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