我需要提取某个路径的父目录的名称。这就是它的样子:
c:\stuff\directory_i_need\subdir\file
我正在修改“文件”的内容,其中使用了directory_i_need
名称(而不是路径)。我已经创建了一个函数,它将给我一个所有文件的列表,然后。。。
for path in file_list:
#directory_name = os.path.dirname(path) # this is not what I need, that's why it is commented
directories, files = path.split('\\')
line_replace_add_directory = line_replace + directories
# this is what I want to add in the text, with the directory name at the end
# of the line.
我该怎么做?
在Python 3.4中,可以使用pathlib module:
你可以继续这样做,只要有必要。。。
编辑:在os.path中,可以使用os.path.split或os.path.basename:
首先,看看是否有
splitunc()
作为os.path
中的可用函数。返回的第一个项目应该是您想要的。。。但是我在Linux上,当我导入os
并尝试使用它时,我没有这个功能。否则,完成工作的一个半丑陋的方法是:
它显示了检索文件上方的目录,以及文件上方的目录。
相关问题 更多 >
编程相关推荐