100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Python

File Handling in Python

Understand how to open, read, write, and close files in Python using the built-in open() function and file modes.

Modules, Files & IterablesBeginner8 min readJul 7, 2026
Analogies

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

python
# 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

python
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

text
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

Was this page helpful?

Topics covered

#Python#PythonProgrammingStudyNotes#Programming#FileHandlingInPython#File#Handling#Syntax#Explanation#StudyNotes#SkillVeris