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

17,382

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.

Share:
17,382
Bruno Gelb
Author by

Bruno Gelb

Updated on June 04, 2022

Comments

  • Bruno Gelb
    Bruno Gelb almost 2 years

    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'