string – How to get the filename without the extension from a path in Python?

string – How to get the filename without the extension from a path in Python?

Getting the name of the file without the extension:

import os
print(os.path.splitext(/path/to/some/file.txt)[0])

Prints:

/path/to/some/file

Documentation for os.path.splitext.

Important Note: If the filename has multiple dots, only the extension after the last one is removed. For example:

import os
print(os.path.splitext(/path/to/some/file.txt.zip.asc)[0])

Prints:

/path/to/some/file.txt.zip

See other answers below if you need to handle that case.

Use .stem from pathlib in Python 3.4+

from pathlib import Path

Path(/root/dir/sub/file.ext).stem

will return

file

Note that if your file has multiple extensions .stem will only remove the last extension. For example, Path(file.tar.gz).stem will return file.tar.

string – How to get the filename without the extension from a path in Python?

You can make your own with:

>>> import os
>>> base=os.path.basename(/root/dir/sub/file.ext)
>>> base
file.ext
>>> os.path.splitext(base)
(file, .ext)
>>> os.path.splitext(base)[0]
file

Important note: If there is more than one . in the filename, only the last one is removed. For example:

/root/dir/sub/file.ext.zip -> file.ext

/root/dir/sub/file.ext.tar.gz -> file.ext.tar

See below for other answers that address that.

Leave a Reply

Your email address will not be published. Required fields are marked *