You can extract the file extension of a filename string using the os. path. splitext method. It splits the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period.
To remove the extension from a filename using Python, the easiest way is with the os module path. basename() and path. splitext() functions. You can also use the pathlib module and Path and then access the attribute 'stem' to remove the extension from a filename.
The Path.GetFileNameWithoutExtension
method gives you the filename you pass as an argument without the extension, as should be obvious from the name.
There's a method in the framework for this purpose, which will keep the full path except for the extension.
System.IO.Path.ChangeExtension(path, null);
If only file name is needed, use
System.IO.Path.GetFileNameWithoutExtension(path);
You can use
string extension = System.IO.Path.GetExtension(filename);
And then remove the extension manually:
string result = filename.Substring(0, filename.Length - extension.Length);
String.LastIndexOf would work.
string fileName= "abc.123.txt";
int fileExtPos = fileName.LastIndexOf(".");
if (fileExtPos >= 0 )
fileName= fileName.Substring(0, fileExtPos);
If you want to create full path without extension you can do something like this:
Path.Combine( Path.GetDirectoryName(fullPath), Path.GetFileNameWithoutExtension(fullPath))
but I'm looking for simpler way to do that. Does anyone have any idea?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With