Python (Scripting) - Determine file encoding (ascii utf)

by
Jeremy Canfield |
Updated: November 06 2023
| Python (Scripting) articles
The magic module can be used to determine a files encoding, such as us-ascii or utf-8. To use the magic module, you will need to install the python-magic packages.
pip install python-magic
Then do something like this to return the encoding.
#!/usr/bin/python3
import magic
blob = open('/path/to/exampe.txt', 'rb').read()
m = magic.open(magic.MAGIC_MIME_ENCODING)
m.load()
encoding = m.buffer(blob)
print(f"example.txt encoding = {encoding}")
Which should return something like this.
example.txt encoding = utf-8
Did you find this article helpful?
If so, consider buying me a coffee over at