Is there a way in Python to check a file name to see if its extension is included in the name? My current workaround is to simply check if the name contains a . in it, and add an extension if it doesn't...this obviously won't catch files with . but no extension in the name (ie. 12.10.13_file). Anyone have any ideas?
Asked
Active
Viewed 6,988 times
2
-
4And why would `13_file` *not* be an extension? You'll need to define some rules as to what makes a valid extension here. There are no standard rules. – Martijn Pieters Oct 15 '14 at 11:50
-
And if you have done that and decide that Martijn is right, use [`os.path.splitext`](https://docs.python.org/3/library/os.path.html#os.path.splitext). It will return a tuple with the filename and the extension (which contains the ., i.e. `.13_file`) or an empty string as the second element. – filmor Oct 15 '14 at 11:53
2 Answers
2
'12.10.13_file' as a filename, does have '13_file' as it's file extension. At least regarding the file system.
But, instead of finding the last . yourself, use os.path.splitext:
import os
fileName, fileExtension = os.path.splitext('/path/yourfile.ext')
# Results in:
# fileName = '/path/yourfile'
# fileExtension = '.ext'
If you want to exclude certain extensions, you could blacklist those after you've used the above.

pyrocumulus
- 9,072
- 2
- 43
- 53
1
You can use libmagic
via https://pypi.python.org/pypi/python-magic to determine "file types." It's not 100% perfect, but a whole lot of files can be accurately classified this way, and then you can decide your own rules, such as .txt
for text files, .pdf
for PDFs, etc.
Don't think in terms of finding files with or without extensions--think of it in terms of classifying your files based on their content, ignoring their current names.

John Zwinck
- 239,568
- 38
- 324
- 436