-3

I have a file path stored as a string in Python, and I need to extract the extension from it. If anyone can share the simplest way to accomplish this task using Python suggestions or code examples I would greatly appreciate it.

Thank You!! :)

petezurich
  • 9,280
  • 9
  • 43
  • 57

3 Answers3

0

Use pathlib:

import pathlib

pathlib.Path("abc.txt").suffix

>>> '.txt'

You'll find more info on pathlib also here.

petezurich
  • 9,280
  • 9
  • 43
  • 57
0

Use os.path.splitext:

import os
file_name, file_ext = os.path.splitext('/path/to/somefile.ext')
print(file_name) # prints '/path/to/somefile'
print(file_ext)  # prints '.ext'
  • This question is already answered before, you can refer to this topic [Extracting extension from filename in Python](https://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python#541394) – Ali Naderi Parizi Jul 03 '23 at 04:59
-1

You can use the os.path module, specifically the splitext() function.

import os

file_path = "/path/to/file.txt"
file_extension = os.path.splitext(file_path)[1]

print(file_extension)  # Output: ".txt"

The os.path.splitext() function splits the file path into the base name and the extension. The function returns a tuple where the first element is the base name and the second element is the extension, including the dot ('.') prefix. In the example above, file_extension will contain the value ".txt".

By using os.path.splitext(), you can handle various file path formats correctly, such as /path/to/file.txt, /path/to/file.tar.gz, or even file.txt without a specific path.

Nethmi_NF
  • 30
  • 5
  • 1
    [don't answer duplicate questions](/help/how-to-answer). find what they're duplicates of, and flag them as [duplicates](/help/duplicates). – starball Jul 03 '23 at 10:11