- Python os.path.splitext() Method
- Syntax
- Parameters
- Return Value
- Example 1: How to Use os.path.splitext() method
- Example 2: Concatenating + operator
- Example 3: Without dot(.) period
- Example 4
- Os path splitext in python
- # Table of Contents
- # Remove the extension from a Filename in Python
- # Remove the extension from a Filename using pathlib.Path
- # Remove the extension from a Filename using removesuffix()
- # Remove the extension from a Filename using str.rsplit()
- # Additional Resources
Python os.path.splitext() Method
Python os.path.splitext() method is “used to split the path name into a pair root and ext .” Here, the ext stands for extension and has the extension portion of the specified path, while the root is everything except ext part.
Syntax
Parameters
path: It is a path-like object representing a file system path. The system path-like object is either a string or bytes representing a path.
Return Value
The splitext() method returns a tuple representing the root and ext part of the specified pathname.
Example 1: How to Use os.path.splitext() method
To extract an extension of a file name in Python, use the os.path.splitext() method. If the ext is empty, the specified path has no extension. It will be ignored if the specified path has a leading period (‘.’).
import os path = "/Users/krunal/Desktop/code/pyt/app.pyt" root_extension = os.path.splitext(path) print("The output tuple", root_extension) print("The root part is: ", root_extension[0]) print("The ext part is: ", root_extension[1])
The output tuple ('/Users/krunal/Desktop/code/pyt/app', '.pyt') The root part is: /Users/krunal/Desktop/code/pyt/app The ext part is: .pyt
You can see that the first output is a complete tuple containing the root and extension of the file path.
The second output is only the root part of the full path.
The third output is only the extension part of the full path.
The os.path.splitext() function splits at the last (right) dot. If you want to split by the first (left) dot, use the os.path.split() function.
To extract a directory name from the file path, use the os.path.dirname() function.
Example 2: Concatenating + operator
Concatenating with the + operator returns the original path string.
import os path = "/Users/krunal/Desktop/code/pyt/app.pyt" root, extension = os.path.splitext(path) print(root) print(extension) full_path = root + extension print(full_path)
/Users/krunal/Desktop/code/pyt/app .pyt /Users/krunal/Desktop/code/pyt/app.pyt
Example 3: Without dot(.) period
To get the extension from a file path without a dot or period in Python, slice the ext part of the splitext() output.
import os path = "/Users/krunal/Desktop/code/pyt/app.pyt" root, extension = os.path.splitext(path) print(root) print(extension[1:])
/Users/krunal/Desktop/code/pyt/app pyt
Example 4
To create a file string with only the extension changed from the original, first concatenate the root of the tuple returned by os.path.splitext() with any extension, and you will have a new file path with a new file name.
import os path = "/Users/krunal/Desktop/code/pyt/app.pyt" root, extension = os.path.splitext(path) print(root) print(extension) new_full_path = root + '.sql' print(new_full_path)
/Users/krunal/Desktop/code/pyt/app .pyt /Users/krunal/Desktop/code/pyt/app.sql
That’s it for this tutorial.
Os path splitext in python
Last updated: Feb 20, 2023
Reading time · 4 min
# Table of Contents
# Remove the extension from a Filename in Python
Use the os.path.splitext() method to remove the extension from a filename.
The os.path.splitext method will return a tuple that contains the filename without the extension as its first element.
Copied!import os file_path = '/home/bobbyhadz/Desktop/my-file.txt' result = os.path.splitext(file_path)[0] # 👇️ '/home/bobbyhadz/Desktop/my-file' print(result) # 👇️ '/home/bobbyhadz/Desktop/my-file.docx' print(result + '.docx')
If you need to split the filename on name and extension, use the following code sample instead.
Copied!import os file_path = '/home/bobbyhadz/Desktop/file.txt' filename, extension = os.path.splitext(file_path) print(filename) # 👉️ '/home/bobbyhadz/Desktop/file' print(extension) # 👉️ '.txt'
We used the os.path.splitext method to remove the extension from a filename.
The os.path.splitext method splits the path into a tuple that contains the root and the extension.
Copied!import os file_path = '/home/bobbyhadz/Desktop/my-file.txt' # 👇️ ('/home/bobbyhadz/Desktop/my-file', '.txt') print(os.path.splitext(file_path))
To get the filename without the extension, access the first element in the tuple.
If the specified path doesn’t contain an extension, the second element in the tuple is an empty string.
Copied!import os file_path = '/home/bobbyhadz/Desktop/my-file' # 👇️ ('/home/bobbyhadz/Desktop/my-file', '') print(os.path.splitext(file_path))
If the provided path doesn’t have an extension, we return the string as is.
Previous periods are ignored if the path contains multiple.
Copied!import os import pathlib file_path = '/home/bobby.hadz/Desktop/my-file.txt' # 👇️ ('/home/bobby.hadz/Desktop/my-file', '.txt') print(os.path.splitext(file_path))
Alternatively, you can use the pathlib.Path() class.
# Remove the extension from a Filename using pathlib.Path
This is a two-step process:
- Instantiate the pathlib.Path() class to create a Path object.
- Use the with_suffix() method to remove the extension from the filename.
Copied!import pathlib file_path = '/home/bobbyhadz/Desktop/my-file.txt' fpath = pathlib.Path(file_path) result = fpath.with_suffix('') print(result) # 👉️ /home/bobbyhadz/Desktop/my-file print(fpath.stem) # 👉️ 'my-file' # 👇️ '/home/bobbyhadz/Desktop/my-file.docx' print(result.with_suffix('.docx'))
If you need to split the filename on the name and the extension, use the following code sample instead.
Copied!import pathlib file_path = '/home/bobbyhadz/Desktop/file.txt' fpath = pathlib.Path(file_path) print(fpath.suffix) # 👉️ '.txt' print(fpath.suffixes) # 👉️ ['.txt'] print(fpath.stem) # 👉️ 'file' print(fpath.parent) # 👉️ '/home/bobbyhadz/Desktop'
The pathlib.Path class is used to create a PosixPath or a WindowsPath object depending on your operating system.
The with_suffix method takes a suffix and changes the suffix of the path.
We first passed an empty string to the method to remove the extension from the filename.
You can optionally call the method with a different extension if you need to add one.
Copied!import pathlib file_path = '/home/bobbyhadz/Desktop/my-file.txt' fpath = pathlib.Path(file_path) result = fpath.with_suffix('') print(result) # 👉️ /home/bobbyhadz/Desktop/my-file print(fpath.stem) # 👉️ 'my-file' # 👇️ '/home/bobbyhadz/Desktop/my-file.docx' print(result.with_suffix('.docx'))
You can use the stem attribute on the Path object if you need to get only the filename without the extension.
# Remove the extension from a Filename using removesuffix()
Alternatively, you can use the removesuffix() method.
Copied!file_path = '/home/bobbyhadz/Desktop/my-file.txt' result = file_path.removesuffix('.txt') print(result) # 👉️ '/home/bobbyhadz/Desktop/my-file' print(result + '.docx') # 👉️ '/home/bobbyhadz/Desktop/my-file.docx'
The str.removesuffix() method is available in Python 3.9+.
The str.removesuffix method checks if the string ends with the specified suffix and if it does, the method returns a new string excluding the suffix, otherwise it returns a copy of the original string.
Copied!# 👇️ '/home/bobbyhadz/Desktop/my-file' print('/home/bobbyhadz/Desktop/my-file.txt'.removesuffix('.txt')) # 👇️ '/home/bobbyhadz/Desktop/my-file' print('/home/bobbyhadz/Desktop/my-file'.removesuffix('.txt'))
If the string doesn’t contain the specified suffix, the method returns the string as is.
Make sure you are running Python version 3.9 or newer to be able to use the str.removesuffix method.
Alternatively, you can use the str.rsplit() method.
# Remove the extension from a Filename using str.rsplit()
This is a three-step process:
- Use the str.rsplit() method to split the filename on a period, once, from the right.
- Access the list item at index 0 .
- The list item at index 0 will contain the filename without the extension.
Copied!file_path = '/home/bobbyhadz/Desktop/my-file.txt' result = file_path.rsplit('.', 1)[0] print(result) # 👉️ '/home/bobbyhadz/Desktop/my-file' print(result + '.docx') # 👉️ '/home/bobbyhadz/Desktop/my-file.docx'
The str.rsplit method returns a list of the words in the string using the provided separator as the delimiter string.
Copied!file_path = '/home/bobbyhadz/Desktop/my-file.txt' # 👇️ ['/home/bobbyhadz/Desktop/my-file', 'txt'] print(file_path.rsplit('.', 1))
The method takes the following 2 arguments:
Name | Description |
---|---|
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At most maxsplit splits are done, the rightmost ones (optional) |
Except for splitting from the right, rsplit() behaves like split() .
We split the filename, once, on a period, from the right.
This approach handles the scenario where the filename doesn’t contain any periods.
Copied!file_path = '/home/bobbyhadz/Desktop/my-file' result = file_path.rsplit('.', 1)[0] print(result) # 👉️ '/home/bobbyhadz/Desktop/my-file'
However, it leads to confusing behavior if the filename contains a period, but doesn’t contain an extension.
Copied!file_path = '/home/bobby.hadz/Desktop/my-file' # 👇️ ['/home/bobby', 'hadz/Desktop/my-file'] print(file_path.rsplit('.', 1)) result = file_path.rsplit('.', 1)[0] print(result) # 👉️ '/home/bobby'
The previously covered approaches are more forgiving in this scenario.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
- Remove all Non-Numeric characters from a String in Python
- Remove everything Before or After a Character in Python
- Remove First and Last Characters from a String in Python
- Remove first occurrence of character from String in Python
- Remove the First N characters from String in Python
- Remove the last N characters from a String in Python
- Remove Newline characters from a List or a String in Python
- Remove non-alphanumeric characters from a Python string
- Remove non-ASCII characters from a string in Python
- Remove the non utf-8 characters from a String in Python
- Remove characters matching Regex from a String in Python
- Remove special characters except Space from String in Python
- How to unzip a .gz file using Python [5 simple Ways]
- How to merge text files in Python [5 simple Ways]
- OSError [Errno 22] invalid argument in Python [Solved]
- How to create a Zip archive of a Directory in Python
- How to recursively delete a Directory in Python
- How to open an HTML file in the Browser using Python
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.