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?
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?
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.
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