Warm tip: This article is reproduced from serverfault.com, please click

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

发布于 2009-03-24 16:41:03

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

For instance, if I had "/path/to/some/file.txt", I would want "file".

Questioner
Joan Venge
Viewed
0
5,043 2020-05-04 06:13:01

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.