2

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' 
9
  • Use raw strings for Windows file names, as the backslashes can be converted into other things...; as in r'E:\That is some string over here\news_20.03_07.30_10 .m2t' Commented Apr 22, 2014 at 8:09
  • 1
    How exactly do you want to differentiate between a file extension and a normal .? Do you want to treat all three-character suffixes delimited by . as extensions? Commented Apr 22, 2014 at 8:12
  • 1
    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. Commented Apr 22, 2014 at 8:20
  • 1
    @aspect_mkn8rd, Then you already have your solution. :) Just download or create a list of extensions that you consider official, and strip any suffix off your filename that is inside that list. By the way, I will write a program tomorrow that uses .bla.mpg as an extension. :P Commented Apr 22, 2014 at 8:21
  • 1
    okay, seems like I get all the situation clearly. Now can you please post these last two comments as answers? I wanna give you two guys rep for your effort and end the question. :) Commented Apr 22, 2014 at 8:23

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.