Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Encode and Decode UTF-8 in Python
Convert a Python string to UTF-8 bytes with .encode() and back to text with .decode(), with a simple demo function.
def encode_decode_demo(text: str):
encoded = text.encode("utf-8")
decoded = encoded.decode("utf-8")
print(f"Original string: {text}")
print(f"Encoded bytes: {encoded}")
print(f"Decoded string: {decoded}")
print(f"Match: {text == decoded}")
if __name__ == "__main__":
encode_decode_demo("Hel…
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 Read a JSON File into a Dictionary in Python
Load a JSON file into a Python dictionary using the json.load() function with proper file handling and UTF-8 encoding.
import json
from pathlib import Path
def read_json_file(filepath: str) -> dict:
"""Read a JSON file and return its contents as a dictionary."""
path = Path(filepath)
with path.open("r", encoding="utf-8") as f:
data = json.load(f)
return data
if __name__ == "__main__":
# Create a sample JS…
How to Strip BOM When Reading UTF-8 Files in Python
Read a UTF-8 text file with Python's pathlib while automatically stripping the Byte Order Mark (BOM) so the first character isn't a hidden glyph.
from pathlib import Path
def read_text_without_bom(file_path):
"""Read a UTF-8 text file, stripping the BOM if present."""
return Path(file_path).read_text(encoding='utf-8-sig')
if __name__ == "__main__":
# Create a sample file with BOM for demonstration
sample_path = Path("sample_with_bom.txt")
…
How to Transcode a File from Latin-1 to UTF-8 in Python
Read a latin1-encoded text file and rewrite it as UTF-8 using Python's pathlib and encoding parameters.
from pathlib import Path
def transcode_to_utf8(input_path, output_path):
"""Read a latin1-encoded file and write it as UTF-8."""
source = Path(input_path)
target = Path(output_path)
with source.open(encoding='latin1') as infile:
content = infile.read()
with target.open('w', encod…
Read Entire File into String with read Method in Python
Open a file, read its entire content into a string using the .read() method, and clean up with a context manager.
from pathlib import Path
def read_file_to_string(file_path: str) -> str:
"""Read the entire file content into a string using the read method."""
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
return content
if __name__ == "__main__":
# Create a temporary file for d…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
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.