Skip to content

Instantly share code, notes, and snippets.

@karthicraghupathi
Forked from u1735067/open_chardet.py
Created November 25, 2025 19:10
Show Gist options
  • Select an option

  • Save karthicraghupathi/2db58a41d2705d5d641a0f6ca5bd8cbd to your computer and use it in GitHub Desktop.

Select an option

Save karthicraghupathi/2db58a41d2705d5d641a0f6ca5bd8cbd to your computer and use it in GitHub Desktop.
Chardet (https://github.com/chardet/chardet) automatic open (from CLI example)
from chardet.universaldetector import UniversalDetector
def open_chardet(file, *args, **kwargs):
detector = UniversalDetector()
with open(file, mode='rb') as fh:
for line in fh:
line = bytearray(line)
detector.feed(line)
if detector.done:
break
detector.close()
if detector.result['encoding']:
print('Detected encoding: {} (confidence {})'.format(
detector.result['encoding'],
detector.result['confidence']
))
kwargs['encoding'] = detector.result['encoding']
return open(file, *args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment