如何仅从 link python 中提取文件名

How to extract only the filename from the link python

我有以下 link: '//mypath/link1/link2/link3/link4/this is the folder\123456 (2).txt'

我想分别解压路径+子目录,带扩展名的文件名和不带扩展名的文件名。输出应如下所示:

[//mypath/link1/link2/link3/link4/this is the folder, 123456 (2).txt, 123456]

到目前为止我尝试了什么?

import os
pth = '//mypath/link1/link2/link3/link4/this is the folder\123456 (2).txt'
head, tail = os.path.split(pth)
print([head, tail])

我能够提取路径和文件名,但不能提取不带扩展名的文件名。我该怎么做?

您可以使用string.split()两次。

pth = '//mypath/link1/link2/link3/link4/this is the folder\123456 (2).txt'
path,filename = pth.split('\')
file_no_ex = filename.split(' ')[0]
output = [path,filename,file_no_ex]

输出:

['//mypath/link1/link2/link3/link4/this is the folder', '123456 (2).txt', '123456']