Back to all snippets
Library/Python/Read & Write Files
pythonbeginnerfilesioutilitiescontext-manager

How to implement Read & Write Files in Python

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.

Code Snippet

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)

What is Read & Write Files?

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.

How It Works

  1. 1`open(path, 'r')` returns a file object; the `with` statement calls `__exit__` (which closes the file) on exit.
  2. 2Mode `'r'` reads, `'w'` writes (overwrites), `'a'` appends, `'rb'`/`'wb'` for binary.
  3. 3Always specify `encoding='utf-8'` for text files to avoid platform-dependent encoding issues.
  4. 4`json.load(f)` / `json.dump(data, f)` handle JSON serialisation directly from/to file objects.

Common Use Cases

  • Config files - Read and write application configuration in JSON or plain text
  • Log files - Append log entries to a file for debugging or auditing
  • Data pipelines - Read input data and write processed output to files
  • Report generation - Write computed results to text or CSV files

Key Benefits

  • Context manager guarantees the file is always closed, preventing resource leaks
  • Clean, readable syntax compared to manual open/close calls
  • Works seamlessly with JSON, CSV, and binary files
  • Built-in to Python with no extra dependencies

Common Mistakes to Avoid

  • Opening a file without `with` and forgetting to call `f.close()` — the handle leaks if an exception occurs.
  • Using the default encoding — omitting `encoding='utf-8'` uses the platform default, causing different behaviour on Windows vs Linux.
  • Using `'w'` mode when you mean to append — `'w'` truncates the file to zero bytes before writing.

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more python examples

Frequently Asked Questions

What is the difference between read() and readlines()?

`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.

About This Python Code Snippet

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.

Tags: files, io, utilities, context-manager  | Language: python  | Difficulty: beginner  | Category: Python

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.