Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
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.
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'
…
How to Write Bytes to a File in Python with 'wb'
Write a bytearray buffer to a binary file using Python's open() in 'wb' mode, then read it back to confirm the data.
data = bytearray([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64])
with open("output.bin", "wb") as f:
f.write(data)
with open("output.bin", "rb") as f:
content = f.read()
print(f"Written {len(data)} bytes: {content}")
print(f"As string: {content.decode('ascii')}")
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.