如何从 Python 中的文件路径中提取文件夹路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17057544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:19:48  来源:igfitidea点击:

How can I extract the folder path from file path in Python?

pythonfilepathdirectoryextract

提问by Genspec

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

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

For example T:\Data\DBDesign\DBDesign_93_v141b.mdband I would like to get just T:\Data\DBDesign(excluding the \DBDesign_93_v141b.mdb).

例如T:\Data\DBDesign\DBDesign_93_v141b.mdb,我想得到T:\Data\DBDesign(不包括\DBDesign_93_v141b.mdb)。

I have tried something like this:

我试过这样的事情:

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']

which is not the result that I require (being T:\Data\DBDesign).

这不是我需要的结果(是T:\Data\DBDesign)。

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

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

采纳答案by Sukrit Kalra

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

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

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

Although, I would recommend using the os.path.dirnamefunction 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 abspathfunction too. An example:

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

>>> 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.splitfunction which returns a tuple, as follows.

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

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

回答by Dan Allan

The built-in submodule os.pathhas a function for that very task.

内置的子模块os.path有一个用于该任务的函数。

import os
os.path.dirname('T:\Data\DBDesign\DBDesign_93_v141b.mdb')

回答by SethMMorton

WITH PATHLIB MODULE (UPDATED ANSWER)

使用 PATHLIB 模块(更新的答案)

One should consider using pathlibfor new development. It is in the stdlib for Python3.4, but available on PyPIfor earlier versions. This library provides a more object-orented method to manipulate paths <opinion>and is much easier read and program with </opinion>.

应该考虑使用pathlib进行新的开发。它在 Python3.4 的 stdlib 中,但早期版本的PyPI 上可用。这个库提供了一种更加面向对象的方法来操作路径<opinion>,并且更容易阅读和编程</opinion>

>>> import pathlib
>>> existGDBPath = pathlib.Path(r'T:\Data\DBDesign\DBDesign_93_v141b.mdb')
>>> wkspFldr = existGDBPath.parent
>>> print wkspFldr
Path('T:\Data\DBDesign')

WITH OS MODULE

带操作系统模块

Use the os.pathmodule:

使用os.path模块:

>>> import os
>>> existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
>>> wkspFldr = os.path.dirname(existGDBPath)
>>> print wkspFldr 
'T:\Data\DBDesign'

You can go ahead and assume that if you need to do some sort of filename manipulation it's already been implemented in os.path. If not, you'll still probably need to use this module as the building block.

您可以继续假设,如果您需要进行某种文件名操作,它已经在os.path. 如果没有,您可能仍然需要使用此模块作为构建块。

回答by Victor Lellis

Here is the code:

这是代码:

import os
existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
wkspFldr = os.path.dirname(existGDBPath)
print wkspFldr # T:\Data\DBDesign

回答by Timothy C. Quinn

Here is my little utility helper for splitting paths int file, path tokens:

这是我用于拆分路径 int 文件、路径标记的小实用助手:

import os    
# usage: file, path = splitPath(s)
def splitPath(s):
    f = os.path.basename(s)
    p = s[:-(len(f))-1]
    return f, p

回答by Zipper1365

Anyone trying to do this in the ESRI GIS Table field calculator interface can do this with the Python parser:

任何试图在 ESRI GIS 表字段计算器界面中执行此操作的人都可以使用Python 解析器执行此操作:

PathToContainingFolder =

PathToContainingFolder =

"\".join(!FullFilePathWithFileName!.split("\")[0:-1])

so that

以便

\Users\me\Desktop\New folder\file.txt

\Users\me\Desktop\New folder\file.txt

becomes

变成

\Users\me\Desktop\New folder

\Users\me\Desktop\New 文件夹