Safely read and write files in Python using context managers
Quick Answer
Always use `with open(path, mode) as f:` — the context manager guarantees the file is closed even if an exception occurs, preventing resource leaks.
1# Read a text file
2with open('file.txt', 'r', encoding='utf-8') as f:
3 content = f.read()
4
5# Read line by line (memory efficient for large files)
6with open('file.txt', 'r', encoding='utf-8') as f:
7 for line in f:
8 print(line.strip())
9
10# Write to a text file
11with open('output.txt', 'w', encoding='utf-8') as f:
12 f.write('Hello, World!\n')
13
14# Append to a file
15with open('log.txt', 'a', encoding='utf-8') as f:
16 f.write('New log entry\n')
17
18# Read and write JSON
19import json
20
21with open('data.json', 'r') as f:
22 data = json.load(f)
23
24with open('data.json', 'w') as f:
25 json.dump(data, f, indent=2)Python's context manager (the with statement) is the safest way to read and write files because it automatically closes the file handle even if an exception occurs. This snippet covers reading text files, writing text, appending content, and working with JSON files — all of which are essential for everyday Python development.
`f.read()` returns the entire file as a single string. `f.readlines()` returns a list of lines. For large files, iterate directly over `f` line by line to avoid loading everything into memory at once.
This free python code snippet for read & write files is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement read & write files quickly and correctly.
All snippets in the Snippetly library follow python best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses python.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.