Get the file extension in python

There are several ways to get the file extension in Python. There are three options here:

  1. Using the os.path module:
import os

filename = 'example.txt'
extension = os.path.splitext(filename)[1]
print(extension)  # Output: '.txt'
  1. Use the pathlib module (available in Python 3.4 and later):
from pathlib import Path

filename = 'example.txt'
extension = Path(filename).suffix
print(extension)  # Output: '.txt'
  1. Use string manipulation:
filename = 'example.txt'
extension = filename[filename.rindex('.'):]
print(extension)  # Output: '.txt'

Note: In this case, we use the rindex() method to find the index of the last occurrence of the '.' character, then we use string slicing to get the characters from that index to the end of the string. This method is less efficient than the previous two, but may be sufficient for simple cases.

Guess you like

Origin blog.csdn.net/iuv_li/article/details/128601552