Reference library

Files & data

Read and write files safely; parse JSON, CSV, and common text formats.

1 match
Files & data easy

How to Detect File Encoding: UTF-8 vs Latin-1 in Python

Detect whether a file is UTF-8 or Latin-1 encoded by attempting a UTF-8 decode and falling back to Latin-1.

file-encoding utf-8 latin-1
Python
import sys

def detect_encoding(file_path):
    with open(file_path, 'rb') as f:
        raw = f.read()
    
    try:
        raw.decode('utf-8')
        return 'UTF-8'
    except UnicodeDecodeError:
        return 'latin1'

if __name__ == "__main__":
    file_path = sys.argv[1] if len(sys.argv) > 1 else 'sample.txt'
…
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Files & data — Python code examples

What you will find here

This page collects files & data snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.