How to find file extensions with Python

Asked 2 years ago, Updated 2 years ago, 125 views

I want to extract the extension from the file path. Isn't there a proper function?

python file-name

2022-09-22 22:34

1 Answers

This feature is implemented in os.path.splitext(path). splitext(path) returns the result of dividing the path by = root + ext.

Note that ext can be an empty string or can start with '.'

import os

fname, ext = os.path.splitext('/path/mytxt.txt')
print fname
print ext

fname, ext = os.path.splitext('.path/mytxt.txt')
print fname
print ext

Results)

/path/mytxt
.txt
.path/mytxt
.txt


2022-09-22 22:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.