如何从 Python 中的文件路径中提取文件夹路径? [英] How can I extract the folder path from file path in Python?

查看:55
本文介绍了如何从 Python 中的文件路径中提取文件夹路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想获取从完整路径到文件的文件夹路径.

例如 T:DataDBDesignDBDesign_93_v141b.mdb 我只想得到 T:DataDBDesign(不包括 DBDesign_93_v141b.mdb).

我尝试过这样的事情:

existGDBPath = r'T:DataDBDesignDBDesign_93_v141b.mdb'wkspFldr = str(existGDBPath.split('\')[0:-1])打印 wkspFldr

但它给了我这样的结果:

['T:', 'Data', 'DBDesign']

这不是我需要的结果(即 T:DataDBDesign).

关于如何获取文件路径的任何想法?

解决方案

使用 split 功能时,您就快到了.你只需要加入字符串,如下所示.

<预><代码>>>>导入操作系统>>>'\'.join(existGDBPath.split('\')[0:-1])'T:\数据\DBDesign'

虽然,我建议使用 os.path.dirname 函数来执行此操作,您只需要传递字符串,它就会为您完成这项工作.由于您似乎在使用 Windows,因此也可以考虑使用 abspath 函数.一个例子:

<预><代码>>>>导入操作系统>>>os.path.dirname(os.path.abspath(existGDBPath))'T:\数据\DBDesign'

如果想要分割后的文件名和目录路径,可以使用返回元组的os.path.split函数,如下所示.

<预><代码>>>>导入操作系统>>>os.path.split(os.path.abspath(existGDBPath))('T:\Data\DBDesign', 'DBDesign_93_v141b.mdb')

I would like to get just the folder path from the full path to a file.

For example T:DataDBDesignDBDesign_93_v141b.mdb and I would like to get just T:DataDBDesign (excluding the DBDesign_93_v141b.mdb).

I have tried something like this:

existGDBPath = r'T:DataDBDesignDBDesign_93_v141b.mdb'
wkspFldr = str(existGDBPath.split('\')[0:-1])
print wkspFldr 

but it gave me a result like this:

['T:', 'Data', 'DBDesign']

which is not the result that I require (being T:DataDBDesign).

Any ideas on how I can get the path to my file?

解决方案

You were almost there with your use of the split function. You just needed to join the strings, like follows.

>>> import os
>>> '\'.join(existGDBPath.split('\')[0:-1])
'T:\Data\DBDesign'

Although, I would recommend using the os.path.dirname function to do this, you just need to pass the string, and it'll do the work for you. Since, you seem to be on windows, consider using the abspath function too. An example:

>>> import os
>>> os.path.dirname(os.path.abspath(existGDBPath))
'T:\Data\DBDesign'

If you want both the file name and the directory path after being split, you can use the os.path.split function which returns a tuple, as follows.

>>> import os
>>> os.path.split(os.path.abspath(existGDBPath))
('T:\Data\DBDesign', 'DBDesign_93_v141b.mdb')

这篇关于如何从 Python 中的文件路径中提取文件夹路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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