我有:
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]
,但这可能不是您想要的,因为文件名包含句点是完全合法的。
关于python - 从文件路径仅获取文件名(不带扩展名和目录),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23213850/