如何从Python的文件路径中提取文件夹路径? [英] How can I extract the folder path from file path in Python?
问题描述
我只想获取从完整路径到文件的文件夹路径.
I would like to get just the folder path from the full path to a file.
例如T:\Data\DBDesign\DBDesign_93_v141b.mdb
,而我只想获取T:\Data\DBDesign
(不包括\DBDesign_93_v141b.mdb
).
For example T:\Data\DBDesign\DBDesign_93_v141b.mdb
and I would like to get just T:\Data\DBDesign
(excluding the \DBDesign_93_v141b.mdb
).
我尝试过这样的事情:
existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
wkspFldr = str(existGDBPath.split('\\')[0:-1])
print wkspFldr
但是它给了我这样的结果:
but it gave me a result like this:
['T:', 'Data', 'DBDesign']
这不是我要求的结果(T:\Data\DBDesign
).
which is not the result that I require (being T:\Data\DBDesign
).
关于如何获取文件路径的任何想法?
Any ideas on how I can get the the path to my file?
推荐答案
使用split
函数几乎可以到那里.您只需要加入字符串即可,如下所示.
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'
尽管,我建议使用os.path.dirname
函数执行此操作,您只需要传递字符串即可,它将为您完成工作.由于您似乎在Windows上,因此也考虑使用abspath
函数.一个例子:
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'
如果要在拆分后同时需要文件名和目录路径,则可以使用os.path.split
函数,该函数返回一个元组,如下所示.
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屋!