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

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 0b14a1 in the box below so that we can be sure you are a human.