Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 236
Joan Venge Avatar asked Mar 24 '09 16:03

Joan Venge


People also ask

How can I find the filename without path?

Use the substring() method to get the filename without the path, e.g. fullPath. substring(fullPath. lastIndexOf('/') + 1) . The substring method will return a new string containing only the characters after the last slash.

How do I read a filename from the path in Python?

To get a filename from a path in Python, use the os. path. basename() function.

How do I separate filenames and extensions in Python?

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.


1 Answers

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.

like image 55
Geo Avatar answered Oct 01 '22 11:10

Geo