Advertisement
Advertisement


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


Question

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".

2020/07/11
1
1055
7/11/2020 5:52:39 PM

Accepted Answer

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.

2020/05/03
1362
5/3/2020 10:13:01 PM


Using pathlib in Python 3.4+

from pathlib import Path

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

will return

'file'
2020/02/26

>>> print(os.path.splitext(os.path.basename("/path/to/file/hemanth.txt"))[0])
hemanth
2020/07/26

In Python 3.4+ you can use the pathlib solution

from pathlib import Path

print(Path(your_path).resolve().stem)
2019/10/11

https://docs.python.org/3/library/os.path.html

In python 3 pathlib "The pathlib module offers high-level path objects." so,

>>> from pathlib import Path
>>> p = Path("/a/b/c.txt")
>>> print(p.with_suffix(''))
\a\b\c
>>> print(p.stem)
c
2018/07/23

If you want to keep the path to the file and just remove the extension

>>> file = '/root/dir/sub.exten/file.data.1.2.dat'
>>> print ('.').join(file.split('.')[:-1])
/root/dir/sub.exten/file.data.1.2
2013/10/21

Source: https://stackoverflow.com/questions/678236
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]