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!! :)
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!! :)
Use pathlib:
import pathlib
pathlib.Path("abc.txt").suffix
>>> '.txt'
You'll find more info on pathlib also here.
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'
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.