|
import pandas as pd |
|
import chardet |
|
import ftfy |
|
|
|
def read_csv_with_encoding(file_path): |
|
|
|
with open(file_path, 'rb') as f: |
|
result = chardet.detect(f.read()) |
|
encoding = result['encoding'] |
|
|
|
|
|
try: |
|
df = pd.read_csv(file_path, encoding=encoding) |
|
return df |
|
except UnicodeDecodeError: |
|
|
|
for enc in ['utf-8', 'latin-1', 'cp1252']: |
|
try: |
|
df = pd.read_csv(file_path, encoding=enc, errors='replace') |
|
return df |
|
except UnicodeDecodeError: |
|
pass |
|
|
|
|
|
with open(file_path, 'rb') as f: |
|
text = f.read().decode('latin-1', errors='replace') |
|
fixed_text = ftfy.fix_text(text) |
|
|
|
try: |
|
df = pd.read_csv(io.StringIO(fixed_text), encoding='utf-8') |
|
return df |
|
except UnicodeDecodeError: |
|
print(f"Failed to read {file_path} after trying multiple encodings and text fixes.") |
|
return None |
|
|
|
|
|
file_path = 'path/to/your/csv/file.csv' |
|
df = read_csv_with_encoding(file_path) |
|
if df is not None: |
|
print(df.head()) |
|
else: |
|
print("Failed to read the CSV file.") |