在Python中获取文件的文件夹名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33372054/
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
Get folder name of the file in Python
提问by Vasily
In Python what command should I use to get the name of the folder which contains the file I'm working with?
在 Python 中,我应该使用什么命令来获取包含我正在使用的文件的文件夹的名称?
"C:\folder1\folder2\filename.xml"
"C:\folder1\folder2\filename.xml"
Here "folder2"
is what I want to get.
这"folder2"
是我想要的。
The only thing I've come up with is to use os.path.split
twice:
我唯一想到的是使用os.path.split
两次:
folderName = os.path.split(os.path.split("C:\folder1\folder2\filename.xml")[0])[1]
folderName = os.path.split(os.path.split("C:\folder1\folder2\filename.xml")[0])[1]
Is there any better way to do it?
有没有更好的方法来做到这一点?
采纳答案by fedorqui 'SO stop harming'
You can use dirname
:
您可以使用dirname
:
os.path.dirname(path)
Return the directory name of pathname path. This is the first element of the pair returned by passing path to the function split().
os.path.dirname(path)
返回路径名路径的目录名。这是通过将路径传递给函数 split() 返回的元素对的第一个元素。
And given the full path, then you can split normally to get the last portion of the path. For example, by using basename
:
并给出完整路径,然后您可以正常拆分以获得路径的最后一部分。例如,通过使用basename
:
os.path.basename(path)
Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split(). Note that the result of this function is different from the Unix basename program; where basename for '/foo/bar/' returns 'bar', the basename() function returns an empty string ('').
os.path.basename(path)
返回路径名路径的基本名称。这是通过将路径传递给函数 split() 返回的对的第二个元素。请注意,此函数的结果与 Unix basename 程序不同;其中 '/foo/bar/' 的 basename 返回 'bar',basename() 函数返回一个空字符串 ('')。
All together:
全部一起:
>>> import os
>>> path=os.path.dirname("C:/folder1/folder2/filename.xml")
>>> path
'C:/folder1/folder2'
>>> os.path.basename(path)
'folder2'
回答by Anand S Kumar
os.path.dirname
is what you are looking for -
os.path.dirname
是你要找的 -
os.path.dirname(r"C:\folder1\folder2\filename.xml")
Make sure you prepend r
to the string so that its considered as a raw string.
确保r
在字符串前面加上,以便将其视为原始字符串。
Demo -
演示 -
In [46]: os.path.dirname(r"C:\folder1\folder2\filename.xml")
Out[46]: 'C:\folder1\folder2'
If you just want folder2
, you can use os.path.basename
with the above, Example -
如果你只是想要folder2
,你可以使用os.path.basename
上面的例子 -
os.path.basename(os.path.dirname(r"C:\folder1\folder2\filename.xml"))
Demo -
演示 -
In [48]: os.path.basename(os.path.dirname(r"C:\folder1\folder2\filename.xml"))
Out[48]: 'folder2'
回答by idjaw
You are looking to use dirname. If you only want that one directory, you can use os.path.basename,
您正在寻找使用dirname。如果你只想要那个目录,你可以使用os.path.basename,
When put all together it looks like this:
放在一起时,它看起来像这样:
os.path.basename(os.path.dirname('dir/sub_dir/other_sub_dir/file_name.txt'))
That should get you "other_sub_dir"
那应该让你“other_sub_dir”
The following is not the ideal approach, but I originally proposed,using os.path.split, and simply get the last item. which would look like this:
以下不是理想的方法,但我最初提出,使用os.path.split,并简单地获取最后一项。看起来像这样:
os.path.split(os.path.dirname('dir/sub_dir/other_sub_dir/file_name.txt'))[-1]
回答by dfresh22
this is pretty old, but if you are using Python 3.4 or above use PathLib.
这已经很老了,但是如果您使用的是 Python 3.4 或更高版本,请使用PathLib。
# using OS
import os
path=os.path.dirname("C:/folder1/folder2/filename.xml")
print(path)
print(os.path.basename(path))
# using pathlib
import pathlib
path = pathlib.PurePath("C:/folder1/folder2/filename.xml")
print(path.parent)
print(path.parent.name)
回答by tjd sydney
You could get the full path as a string then split it into a list using your operating system's separator character. Then you get the program name, folder name etc by accessing the elements from the end of the list using negative indices.
您可以将完整路径作为字符串获取,然后使用操作系统的分隔符将其拆分为列表。然后通过使用负索引访问列表末尾的元素来获取程序名称、文件夹名称等。
Like this:
像这样:
import os
strPath = os.path.realpath(__file__)
print( f"Full Path :{strPath}" )
nmFolders = strPath.split( os.path.sep )
print( "List of Folders:", nmFolders )
print( f"Program Name :{nmFolders[-1]}" )
print( f"Folder Name :{nmFolders[-2]}" )
print( f"Folder Parent:{nmFolders[-3]}" )
The output of the above was this:
上面的输出是这样的:
Full Path :C:\Users\terry\Documents\apps\environments\dev\app_02\app_02.py
List of Folders: ['C:', 'Users', 'terry', 'Documents', 'apps', 'environments', 'dev', 'app_02', 'app_02.py']
Program Name :app_02.py
Folder Name :app_02
Folder Parent:dev