How to detect the Text Encoding of a File in Python
Having the ability to determine a file’s text encoding can be really useful, but a bit of a pain to code the solution yourself. It is my mission today to save you from this suffering. And so we shall use an API that will handle this problem in our stead. Total time required: a couple minutes. Let’s get started with our client installation with the below command:
pip install cloudmersive-convert-api-client
Now we are going to call our function, which is pretty simple. Just follow this example code to get started.
from __future__ import print_functionimport timeimport cloudmersive_convert_api_clientfrom cloudmersive_convert_api_client.rest import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_convert_api_client.Configuration()configuration.api_key['Apikey'] = 'YOUR_API_KEY'# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed# configuration.api_key_prefix['Apikey'] = 'Bearer'# create an instance of the API classapi_instance = cloudmersive_convert_api_client.EditTextApi(cloudmersive_convert_api_client.ApiClient(configuration))input_file = '/path/to/file' # file | Input file to perform the operation on.try:# Detect text encoding of fileapi_response = api_instance.edit_text_text_encoding_detect(input_file)pprint(api_response)except ApiException as e:print("Exception when calling EditTextApi->edit_text_text_encoding_detect: %s\n" % e)
Congratulations, you now have text encoding detection in your project! Piece of cake.