| 1 |
|
| 2 |
|
| 3 |
"""Functionality to detect file encodings |
| 4 |
|
| 5 |
Author: G.J.J. van den Burg |
| 6 |
License: See the LICENSE file |
| 7 |
|
| 8 |
This file is part of CleverCSV. |
| 9 |
|
| 10 |
""" |
| 11 |
|
| 12 |
from typing import Optional |
| 13 |
|
| 14 |
import chardet |
| 15 |
|
| 16 |
from ._optional import import_optional_dependency |
| 17 |
from ._types import _OpenFile |
| 18 |
|
| 19 |
|
| 20 |
def get_encoding( |
| 21 |
filename: _OpenFile, try_cchardet: bool = True |
| 22 |
) -> Optional[str]: |
| 23 |
"""Get the encoding of the file |
| 24 |
|
| 25 |
This function uses the chardet package for detecting the encoding of a |
| 26 |
file. |
| 27 |
|
| 28 |
Parameters |
| 29 |
---------- |
| 30 |
filename: str |
| 31 |
Path to a file |
| 32 |
|
| 33 |
try_cchardet: bool |
| 34 |
Whether to run detection using cChardet if it is available. This can be |
| 35 |
faster, but may give different results than using chardet. |
| 36 |
|
| 37 |
Returns |
| 38 |
------- |
| 39 |
encoding: str |
| 40 |
Encoding of the file. |
| 41 |
""" |
| 42 |
if try_cchardet: |
| 43 |
cchardet = import_optional_dependency( |
| 44 |
"cchardet", raise_on_missing=False |
| 45 |
) |
| 46 |
else: |
| 47 |
cchardet = None |
| 48 |
|
| 49 |
if cchardet is None: |
| 50 |
detector = chardet.UniversalDetector() |
| 51 |
else: |
| 52 |
detector = cchardet.UniversalDetector() |
| 53 |
|
| 54 |
final_chunk = False |
| 55 |
blk_size = 65536 |
| 56 |
with open(filename, "rb") as fid: |
| 57 |
while (not final_chunk) and (not detector.done): |
| 58 |
chunk = fid.read(blk_size) |
| 59 |
if len(chunk) < blk_size: |
| 60 |
final_chunk = True |
| 61 |
detector.feed(chunk) |
| 62 |
detector.close() |
| 63 |
encoding = detector.result.get("encoding", None) |
| 64 |
return encoding |