仅从文件路径获取文件名(不带扩展名和目录)
我现在拥有的内容是:
import os
import ntpath
def fetch_name(filepath):
return os.path.splitext(ntpath.basename(filepath))[0]
a = u'E:\That is some string over here\news_20.03_07.30_10 .m2t'
b = u'E:\And here is some string too\Logo_TimeBuffer.m2t.mpg'
fetch_name(a)
>>u'That is some string over here\news_20.03_07.30_10 ' # wrong!
fetch_name(b)
>>u'Logo_TimeBuffer.m2t' # wrong!
我需要的内容是:
fetch_name(a)
>>u'news_20.03_07.30_10 '
fetch_name(b)
>>u'Logo_TimeBuffer'
1 个回答
5
你的代码运行得非常正常。在例子a中,\n并不是被当作反斜杠字符来处理,而是作为换行符。在例子b中,扩展名是.mpg,这个扩展名被正确地去掉了。一个文件不可能有多个扩展名,或者有包含点的扩展名。
如果你只想获取第一个点之前的部分,可以使用ntpath.basename(filepath).split('.')[0]
,但这可能并不是你想要的,因为文件名中包含点是完全合法的。