Чтобы распечатать кодировку файла в Python, вы можете использовать следующие методы:
Метод 1. Использование библиотеки chardet:
import chardet
def get_file_encoding(file_path):
with open(file_path, 'rb') as file:
result = chardet.detect(file.read())
return result['encoding']
file_path = 'path/to/your/file'
encoding = get_file_encoding(file_path)
print("File encoding:", encoding)
Способ 2. Использование команды file(Linux/macOS):
import subprocess
def get_file_encoding(file_path):
result = subprocess.run(['file', '--mime', '-b', file_path], capture_output=True, text=True)
encoding = result.stdout.split(';')[1].strip().split('=')[1]
return encoding
file_path = 'path/to/your/file'
encoding = get_file_encoding(file_path)
print("File encoding:", encoding)
Метод 3. Использование модуля кодеки:
import codecs
def get_file_encoding(file_path):
with codecs.open(file_path, 'r', encoding='utf-8', errors='ignore') as file:
return file.encoding
file_path = 'path/to/your/file'
encoding = get_file_encoding(file_path)
print("File encoding:", encoding)
Метод 4. Использование библиотеки charset-normalizer:
from charset_normalizer import CharsetNormalizerMatches as CnM
def get_file_encoding(file_path):
with open(file_path, 'rb') as file:
result = CnM.from_fp(file)
return result.best().first()
file_path = 'path/to/your/file'
encoding = get_file_encoding(file_path)
print("File encoding:", encoding)