我所拥有的:
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'
你的代码工作正常。在示例a中,\n不被视为反斜杠字符,因为它是换行字符。在示例b中,扩展名是.mpg,该扩展名已正确删除。一个文件不能有多个扩展名,也不能有包含句点的扩展名。
要只获取第一个句点之前的位,可以使用
ntpath.basename(filepath).split('.')[0]
,但这可能不是您想要的,因为文件名包含句点是完全合法的。相关问题 更多 >
编程相关推荐