[Tutor] getting filen basename without extension

Alan Gauld alan.gauld at btinternet.com
Thu Jan 10 14:07:09 CET 2008

"Timmie" <timmichelsen at gmx-topmail.de> wrote 

> What is the easiest and fastes way to get the basename
> of a file wihout extension?
> What I found is this:
> import os
> myfile_name_with_path = 'path/to/my/testfile.txt'
> basename = os.path.basename(myfile_with_path)
> filename = os.path.splitext(basename)
> myfile_name_without_suffix = filename[0]

The last two can be easily combined as:

> myfile_name_without_suffix = os.path.splitext(basename)[0]

without much loss of clarity.
You could combine the basename call as well of course, 
but that is getting too messy for my liking.

But otherwise you are using the "correct" mechanism if 
you want a reliable result.

Alan G.

More information about the Tutor mailing list