Mastering File Modes in Python: Your Complete Guide

Learn How to Handle File Modes Like a Pro in Python Programming

Max N
2 min readApr 8, 2024

File modes are fundamental to working with files in Python. They determine how a file can be opened, read from, written to, and more.

In this article, we’ll dive into the world of file modes, exploring their types and when to use each one.

Understanding File Modes

File modes specify the purpose and access permissions of a file when it is opened. Here are the most common file modes in Python:

  • ‘r’ (Read mode): Opens a file for reading. It raises an error if the file does not exist.
with open('example.txt', 'r') as file:
data = file.read()
print(data)
  • ‘w’ (Write mode): Opens a file for writing. If the file exists, its contents are overwritten. If the file does not exist, a new file is created.
with open('example.txt', 'w') as file:
file.write('Hello, World!')
  • ‘a’ (Append mode): Opens a file for appending. New data is written to the end of the file. If the file does not exist, a new file is created.
with open('example.txt', 'a') as file:
file.write('\nAppending new content!')

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.