gpt4 book ai didi

python - 在Python中获取文件的文件夹名称

转载 作者:IT老高 更新时间:2023-10-28 20:33:43 25 4
gpt4 key购买 nike

在 Python 中,我应该使用什么命令来获取包含我正在使用的文件的文件夹的名称?

"C:\folder1\folder2\filename.xml"

这里 "folder2" 是我想要得到的。

我想出的唯一方法是使用 os.path.split 两次:

folderName = os.path.split(os.path.split("C:\folder1\folder2\filename.xml")[0])[1]

有没有更好的办法?

最佳答案

您可以使用 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().

并且给定完整路径,然后您可以正常拆分以获取路径的最后一部分。例如,使用 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 ('').


大家一起:

>>> import os
>>> path=os.path.dirname("C:/folder1/folder2/filename.xml")
>>> path
'C:/folder1/folder2'
>>> os.path.basename(path)
'folder2'

关于python - 在Python中获取文件的文件夹名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33372054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com