Working with Files in Python: Reading and Writing Made Easy
In programming, you often need to save data permanently or read data from files. Python provides simple and powerful tools to work with files — whether you want to read a text file, write logs, or process data.
This guide will introduce you to the basics of file handling in Python.
Basic File Operations
Python uses the built-in open() function to open files. When you open a file, you get a file object that lets you read, write, or modify the file.
Opening a File
Syntax:
-
"r"— read (default mode) -
"w"— write (creates or overwrites file) -
"a"— append (add to end of file) -
"b"— binary mode (used with other modes, e.g.,"rb")
Reading from a File
Example: Read the entire file
-
Using
withautomatically closes the file after the block finishes — best practice! -
.read()reads the whole file as a string.
Read line by line
✍️ Writing to a File
Overwrite or create a file
This will create output.txt or overwrite it if it exists.
Append to a file
️ Other Useful Methods
-
.readline()— reads one line at a time. -
.readlines()— reads all lines into a list.
Example:
⚠️ Important Tips
-
Always use
with open(...)to ensure files are properly closed. -
Be careful with write mode
"w"— it overwrites existing files. -
Use binary mode (
"rb","wb") for non-text files like images.
Summary
| Operation | Mode | Description |
|---|---|---|
| Read | "r" |
Open file for reading |
| Write | "w" |
Open file for writing (overwrite) |
| Append | "a" |
Open file to add data at the end |
| Binary read | "rb" |
Read non-text files |
| Binary write | "wb" |
Write non-text files |
