1

I want to check string is valid extension in Python.

For example, I have string png or .png and I want to check if it is exist extension. So I think I need list of extensions like ["png", "jpg", "pdf", "txt", ....] but I can't find it anywhere.

Does anyone have a way to do this or have a list of extensions?

I'm using Python 3.8, and Window 10. Thanks.

Danis
  • 344
  • 2
  • 13
Superjay
  • 447
  • 1
  • 7
  • 25
  • do you only want list of extensions? – Prakash Dahal Jan 31 '21 at 02:02
  • What do you need this for? What do you consider as a valid extension? You can just define the list yourself depending on your application use case (ex. all supported image formats). If there is some app that outputs data in its own extension `.abc` or `.configfile`, should that be also on this list? – Gino Mempin Jan 31 '21 at 02:12
  • If you have filenames, you can refer to [this post](https://stackoverflow.com/questions/10937350/how-to-check-type-of-files-without-extensions-in-python) about inferring the file type, and then checking if that matches the file's extension. Or, just use the [`mimetypes` library](https://docs.python.org/3/library/mimetypes.html) to look up the mime type and validate it that way. – costaparas Jan 31 '21 at 02:15

1 Answers1

0

“Valid extension” has no sense as extensions are purely arbitrary representation metadata. You can for instance open a PNG file whose name does not end with .png in any image viewer (blatantly ill-behaved exceptions aside). Files actually do not even need to have an extension at all.

If what you want is an extension list to be used in contexts like file pickers (that filter files according to their extension), then that list is up to your application domain: you must define what file types (and hence their common extensions) you want to support.

For a (long but still not exhaustive) list of common file extensions, you may check out websites such as http://www.fileextension.org or https://www.extension.info (many others exist).

michaeldel
  • 2,204
  • 1
  • 13
  • 19