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

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

问题描述

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

C:folder1folder2filename.xml"

这里"folder2"是我想要的.

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

folderName = os.path.split(os.path.split("C:folder1folder2filename.xml")[0])[1]

有什么更好的方法吗?

解决方案

您可以使用 目录名:

<块引用>

os.path.dirname(path)

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

并且给定完整路径,那么您可以正常拆分以获得路径的最后一部分.例如,通过使用 basename:

<块引用>

os.path.basename(path)

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

<小时>

一起:

<预><代码>>>>导入操作系统>>>path=os.path.dirname("C:/folder1/folder2/filename.xml")>>>小路'C:/文件夹 1/文件夹 2'>>>os.path.basename(路径)'文件夹 2'

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

"C:folder1folder2filename.xml"

Here "folder2" is what I want to get.

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

folderName = os.path.split(os.path.split("C:folder1folder2filename.xml")[0])[1]

Is there any better way to do it?

解决方案

You can use 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().

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)

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天全站免登陆