1. Introduction
File handling lets a Python program persist data beyond a single run by reading from and writing to files on disk. Python's built-in open() function returns a file object that supports reading, writing, and closing, and works with text files as well as binary files such as images.
Cricket analogy: A team keeps a physical scorebook so match statistics survive beyond the day's play, and the scorer's pen (open()) can be used to write new entries, read past scores, or record photographs of the trophy presentation alike.
Every file you open should eventually be closed to release the operating system resources associated with it; forgetting to close files can lead to data not being flushed to disk or hitting limits on open file handles.
Cricket analogy: A groundskeeper must roll up and store the covers after every match, since leaving them out unrolled risks damage to the pitch and wastes resources needed for the next fixture.
2. Syntax
# Open a file in a given mode
file = open('example.txt', 'r') # read (text)
file = open('example.txt', 'w') # write (overwrite)
file = open('example.txt', 'a') # append
file = open('example.bin', 'rb') # read binary
file = open('example.bin', 'wb') # write binary
# Core operations
file.write('some text')
data = file.read()
file.close()3. Explanation
The mode string passed to open() controls how the file is accessed: 'r' opens for reading (fails if the file does not exist), 'w' opens for writing and truncates/creates the file, 'a' opens for appending to the end, and adding 'b' (e.g. 'rb', 'wb') switches to binary mode for non-text data. Modes like 'r+' allow both reading and writing.
Cricket analogy: Selecting a batsman purely to defend ('r' mode) fails if there's no pitch to bat on; picking an all-rounder to build a new innings from scratch ('w' mode) overwrites the previous approach entirely, while a specialist finisher ('a' mode) only adds runs at the end without disturbing what's already scored.
After finishing work with a file, call close() to flush any buffered writes to disk and free the file handle. If an exception occurs between open() and close(), the file may never be closed properly.
Cricket analogy: Once the scorer finishes the innings, they must sign off and file the scorebook to lock in the runs; if a rain delay interrupts before sign-off, the book might never get properly filed and closed.
Always close files explicitly, or better, use the 'with' statement (covered in the next topic) so the file is closed automatically even if an error occurs. Relying on manual close() calls risks leaking file handles or losing unflushed data when exceptions happen.
4. Example
import tempfile, os
path = os.path.join(tempfile.gettempdir(), 'demo_file_handling.txt')
f = open(path, 'w')
f.write('Hello, File Handling!\n')
f.write('Second line.')
f.close()
f = open(path, 'r')
content = f.read()
f.close()
print(content)
os.remove(path)5. Output
Hello, File Handling!
Second line.6. Key Takeaways
- open() returns a file object; the mode string ('r', 'w', 'a', 'rb', etc.) controls read/write/append and text/binary behavior.
- 'w' truncates or creates the file; 'a' appends without erasing existing content; 'r' requires the file to already exist.
- Always close a file (or use 'with') to ensure data is flushed and resources are released.
- Binary modes ('rb', 'wb') are needed for non-text data such as images or serialized objects.
- Unhandled exceptions between open() and close() can leave a file unclosed.
Practice what you learned
1. Which mode opens a file for writing and erases its existing contents?
2. What happens if you open a non-existent file with mode 'r'?
3. Which mode should you use to read a JPEG image file correctly?
4. Why is it important to call close() on a file object?
5. What is a key risk of forgetting to close a file after writing to it?
Was this page helpful?
You May Also Like
Reading and Writing Files in Python
Explore the different methods for reading and writing file content, including read(), readline(), readlines(), write(), and writelines().
with Statement (Context Managers) in Python
Learn how the 'with' statement uses the context manager protocol (__enter__/__exit__) to guarantee cleanup, such as automatically closing files.
Working with JSON in Python
Learn how to convert Python objects to and from JSON using the json module, including dumps/loads for strings and dump/load for files.
os Module in Python
Explore Python's os module for interacting with the operating system, including file paths, directories, and environment information.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics