0

Which python function/method/class can I use to detect whether a file is a css file or not?

Which Python exception should I use to indicate that a css file is not detected?

Sun Bear
  • 7,594
  • 11
  • 56
  • 102
  • Possible duplicate of [How to check type of files without extensions in python?](https://stackoverflow.com/questions/10937350/how-to-check-type-of-files-without-extensions-in-python) – Corsaka Oct 04 '19 at 09:52
  • just doing a filename[-4:] == ".css" should work for the first part. – fireball.1 Oct 04 '19 at 09:53

2 Answers2

1

Solution A: Check the file extension. If the file ends with .css it's likely a CSS file. Example: someFilePath[-4:] == ".css"

Solution B: Try to parse the CSS file. Use tinycss or a similar module. If parsing fails the parser will throw an exception. (See: https://tinycss.readthedocs.io/en/latest/parsing.html.)

Regarding exceptions: You can either a) go with something like raise Exception("Not a CSS file") or similar, or b) design a custom exception and raise it. Both things work, both have their advantages and disadvantages. What's best heavily depends on the context. I've no information about details of your implementation, so I can not tell you which option is better.

Regis May
  • 3,070
  • 2
  • 30
  • 51
1

https://docs.python.org/3.7/library/mimetypes.html#mimetypes.guess_type

Maybe your own exception will be the best choice, for example

class CssFileTypeError(Exception):
    pass

raise CssFileTypeError
AngrySoft
  • 101
  • 2
  • Thanks. I chose this solution as it uses `minetypes`, a standard python 3 module, and it can detect css type file. Also, the custom Exception is easy to implement. :) – Sun Bear Oct 04 '19 at 13:28