Extract File Extension in Python Using rindex
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
This Python code extracts the file extension from a filename by finding the position of the last dot using the rindex() method. The filename is assumed to be a string, and the extension is everything after the final dot.
Here's how it works:
- Find the last dot:
last_dot = filename.rindex('.')returns the index of the last occurrence of the dot character. - Extract substring:
extension = filename[last_dot+1:]takes the substring starting right after the dot to the end of the string. - Output: The extension is printed, e.g., "txt".
This method is simple but should be used with caution. If the filename has no dot, rindex() will raise a ValueError. For robust handling, consider using os.path.splitext() or checking for the dot's existence first.