在Python中获取文件的文件夹名称 [英] Get folder name of the file in Python

查看:1659
本文介绍了在Python中获取文件的文件夹名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Python what command should I use to get the name of the folder which contains the file I'm working with?

C:\ folder1\folder2\filename.xml;

这里是 folder2

我唯一想到的就是两次使用 os.path.split

The only thing I've come up with is to use os.path.split twice:

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

有没有更好的方法?

推荐答案

您可以使用 dirname

You can use dirname:


os.path.dirname(path)

返回路径名path的目录名。这是通过将路径传递给函数split()返回的对中的第一个元素

Return the directory name of pathname path. This is the first element of the pair returned by passing path to the function split().

路径,则可以正常拆分以获取路径的最后一部分。例如,使用 basename

And given the full path, then you can split normally to get the last portion of the path. For example, by using basename:


os.path.basename(path)

返回路径名path的基本名称。这是通过将路径传递给函数split()返回的货币对
的第二个元素。注意
这个函数的结果不同于Unix basename
程序; '/ foo / bar /'的基本名称返回'bar',basename()
函数返回一个空字符串('')。

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 ('').






一起:


All together:

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

这篇关于在Python中获取文件的文件夹名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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