Bruno Gelb
Bruno Gelb

Reputation: 5662

Get file name only (without extension and directory) from file path

What I have:

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!

What I need:

fetch_name(a)
>>u'news_20.03_07.30_10 '
fetch_name(b)
>>u'Logo_TimeBuffer'

Upvotes: 2

Views: 18224

Answers (1)

EvertW
EvertW

Reputation: 1180

Your code works exactly as it should. In example a, the \n is not treated as a backslash character because it is a newline character. In example b, the extension is .mpg, which is properly removed. A file can never have more than one extension, or an extension containing a period.

To only get the bit before the first period, you could use ntpath.basename(filepath).split('.')[0], but this is probably NOT what you want as it is perfectly legal for filenames to contain periods.

Upvotes: 5

Related Questions