Beginner
File Handling: Reading and Writing Files
📂 Phase 4: OOP Concepts, File Handling, Exception Handling (Days 16–20) · Python ProgrammingFile handling lets a Python program read from and write to files stored on disk — essential for working with logs, configuration files, datasets, and any data that needs to persist after the program finishes running.
Opening a File With open()
file = open("notes.txt", "r") # "r" = read mode
content = file.read()
print(content)
file.close() # always close a file when you are done with it
File Modes
| Mode | Meaning |
|---|---|
| "r" | Read (default) — error if the file does not exist |
| "w" | Write — creates the file if missing, OVERWRITES existing content entirely |
| "a" | Append — creates the file if missing, adds new content to the END |
| "x" | Create — error if the file already exists |
| "r+" | Read and write, without truncating existing content |
The with Statement — The Recommended Way to Handle Files
with open("notes.txt", "r") as file:
content = file.read()
print(content)
# the file is automatically closed here, even if an error occurred above
Using with is strongly preferred over manually calling open() and close(). If an exception is raised between open() and close(), the file could be left open indefinitely — with guarantees proper cleanup no matter what happens inside the block.
Different Ways to Read a File
with open("notes.txt", "r") as file:
full_text = file.read() # reads the ENTIRE file as one string
with open("notes.txt", "r") as file:
first_line = file.readline() # reads just ONE line
with open("notes.txt", "r") as file:
all_lines = file.readlines() # reads every line into a LIST of strings
with open("notes.txt", "r") as file:
for line in file: # most memory-efficient — reads one line at a time
print(line.strip()) # .strip() removes the trailing newline character
Writing to a File
with open("notes.txt", "w") as file:
file.write("First line of text
")
file.write("Second line of text
")
# IMPORTANT: "w" mode completely erases any existing content first
Appending Instead of Overwriting
with open("notes.txt", "a") as file:
file.write("This line gets added to the end
")
# existing content is preserved; the new line is added after it
Writing Multiple Lines at Once
lines = ["First line
", "Second line
", "Third line
"]
with open("notes.txt", "w") as file:
file.writelines(lines)
Checking If a File Exists Before Opening It
import os
if os.path.exists("notes.txt"):
with open("notes.txt", "r") as file:
print(file.read())
else:
print("File does not exist")
Working With JSON Files
Since JSON is such a common data format, Python's built-in json module makes reading and writing structured data almost effortless.
import json
data = {"name": "Vishwas", "role": "Developer", "city": "Bengaluru"}
# Writing a dictionary to a JSON file
with open("profile.json", "w") as file:
json.dump(data, file)
# Reading it back as a dictionary
with open("profile.json", "r") as file:
loaded_data = json.load(file)
print(loaded_data["name"]) # Vishwas
Interview tip: "What is the difference between read(), readline(), and readlines()?" is a near-guaranteed question — read() returns the whole file as one string, readline() returns just the next single line, and readlines() returns every line as a list of strings; iterating directly over the file object is the most memory-efficient option for very large files, since it never loads the entire file into memory at once.