File size: 1,306 Bytes
9bd34f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import pandas as pd
import chardet
import ftfy

def read_csv_with_encoding(file_path):
    # Detect the file encoding
    with open(file_path, 'rb') as f:
        result = chardet.detect(f.read())
        encoding = result['encoding']

    # Try reading the file with the detected encoding
    try:
        df = pd.read_csv(file_path, encoding=encoding)
        return df
    except UnicodeDecodeError:
        # If the detected encoding fails, try other encodings
        for enc in ['utf-8', 'latin-1', 'cp1252']:
            try:
                df = pd.read_csv(file_path, encoding=enc, errors='replace')
                return df
            except UnicodeDecodeError:
                pass

    # If all encodings fail, try fixing the text
    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

# Example usage
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.")