Reading and writing files
What Is File Handling?
File handling lets you read from, write to, and modify files stored on your computer. Python uses the built-in open() function to interact with files.
Opening a File
file = open(“example.txt”, “mode”)
Modes:
Mode | Description |
---|---|
'r' |
Read (default mode) |
'w' |
Write (overwrites existing file) |
'a' |
Append to end of file |
'x' |
Create a new file (error if file already exists) |
'b' |
Binary mode (e.g., 'rb' , 'wb' ) |
't' |
Text mode (default) |
'+' |
Read and write (updates existing file) |
Reading from a File
Read Entire File
with open(“example.txt”, “r”) as f:
content = f.read()
print(content)
Read Line-by-Line
with open(“example.txt”, “r”) as f:
lines = f.readlines()
Writing to a File
Overwrite (Write Mode ‘w’)
with open(“output.txt”, “w”) as f:
f.write(“Hello, world!\n”)
Append (Append Mode ‘a’)
with open(“output.txt”, “a”) as f:
f.write(“This line will be added.\n”)
Writing Multiple Lines
lines = [“Line 1\n”, “Line 2\n”, “Line 3\n”]
with open(“lines.txt”, “w”) as f:
f.writelines(lines)
Always Use with
The with statement automatically closes the file when done (safer and cleaner than manually using file.close()).
Common Errors
- FileNotFoundError: File does not exist in read mode.
- PermissionError: You don’t have permission to access/write.
- UnicodeDecodeError: Mismatch in encoding.
To fix encoding issues:
with open(“file.txt”, encoding=”utf-8″) as f:
…
Reading/Writing Binary Files
For non-text files (images, PDFs, etc.):
with open(“image.jpg”, “rb”) as f:
data = f.read()
with open(“copy.jpg”, “wb”) as f:
f.write(data)
Summary:
- Use open(filename, mode) to access files.
- Use read(), readline(), or readlines() to read.
- Use write() or writelines() to write.
- Always use with open(…) for safe file handling.
- Choose modes (r, w, a, b, etc.) based on your need.
with statement
What Is the with Statement?
The with statement simplifies resource management by ensuring that setup and cleanup actions (like opening and closing a file) are automatically handled — even if errors occur.
It’s most commonly used for file handling, but applies to any object that supports a “context manager” (i.e., has __enter__() and __exit__() methods).
Syntax
with expression as variable:
# do something with variable
Example (file handling):
with open(“example.txt”, “r”) as f:
content = f.read()
print(content)
# File is automatically closed after this block
Behind the Scenes
When you use:
with open(“file.txt”) as f:
…
It’s roughly equivalent to:
f = open(“file.txt”)
try:
# Do something
finally:
f.close()
But shorter, cleaner, and error-safe.
Benefits of with
- Automatic cleanup: No need to call close() manually.
- Error handling: Ensures proper exit even if an exception occurs.
- Cleaner code: Less boilerplate, more readable.
- Prevents resource leaks: Great for files, sockets, database connections, etc.
Multiple Contexts
You can handle multiple resources in one line:
with open(“in.txt”, “r”) as fin, open(“out.txt”, “w”) as fout:
for line in fin:
fout.write(line.upper())
Custom Context Managers
You can make your own objects usable with with by defining:
class MyContext:
def __enter__(self):
print(“Entered”)
return self
def __exit__(self, exc_type, exc_value, traceback):
print(“Exited”)
with MyContext() as obj:
print(“Inside block”)
Output:
Entered
Inside block
Exited
Common Use Cases
- File handling (open)
- Database connections (sqlite3.connect)
- Thread/lock management (with threading.Lock():)
- Temporary files and directories
- Network sockets
- Custom cleanup routines
Summary:
- The with statement manages setup/teardown automatically.
- It’s used with context managers to write safer, cleaner code.
- Most useful for files, but works for many other resources.
- Saves time and avoids bugs caused by forgetting to release a resource.
Working with CSV and JSON files
CSV (Comma-Separated Values)
CSV files store tabular data as plain text, with each row on a new line and each column separated by commas.
Reading a CSV File
Python provides the built-in csv module:
import csv
with open(“data.csv”, newline=”) as file:
reader = csv.reader(file)
for row in reader:
print(row)
Writing to a CSV File
with open(“output.csv”, “w”, newline=”) as file:
writer = csv.writer(file)
writer.writerow([“Name”, “Age”])
writer.writerow([“Alice”, 30])
Reading as Dictionary
with open(“data.csv”) as file:
reader = csv.DictReader(file)
for row in reader:
print(row[“Name”], row[“Age”])
Writing with DictWriter
with open(“output.csv”, “w”, newline=”) as file:
fieldnames = [“Name”, “Age”]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({“Name”: “Bob”, “Age”: 25})
Common CSV Tips
- Use newline=” on Windows to avoid blank lines.
- Customize the delimiter using csv.reader(file, delimiter=’;’).
JSON (JavaScript Object Notation)
JSON is a lightweight format for structured data, commonly used in APIs and configurations.
Python Data ↔ JSON
Python | JSON |
---|---|
dict |
object |
list / tuple |
array |
str |
string |
int / float |
number |
True / False |
true / false |
None |
null |
Reading JSON from a File
import json
with open(“data.json”, “r”) as file:
data = json.load(file)
print(data)
Writing JSON to a File
with open(“output.json”, “w”) as file:
json.dump(data, file, indent=4)
Converting Between JSON Strings and Python
json_string = ‘{“name”: “Alice”, “age”: 30}’
data = json.loads(json_string) # JSON → Python dict
new_json = json.dumps(data, indent=2) # Python → JSON string
print(new_json)
Pretty Printing JSON
print(json.dumps(data, indent=4, sort_keys=True))
Summary:
Feature | CSV | JSON |
---|---|---|
Type | Flat, tabular data | Nested, structured data |
Module | csv |
json |
Read | csv.reader , csv.DictReader |
json.load() |
Write | csv.writer , csv.DictWriter |
json.dump() |
Use | Excel, spreadsheets, data exports | APIs, configs, data interchange |
Let me know if you’d like examples using Pandas, or want a hands-on challenge to convert CSV to JSON and vice versa!