File Handling in Python
File handling allows Python programs to store data permanently in files instead of keeping it only in memory.
It is used for:
- Saving logs
- Storing user data
- Reading configuration files
- Processing CSV/JSON data
- Working with large datasets
What is File Handling?
File handling refers to the process of performing operations on a file, such as creating, opening, reading, writing and closing it through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely and efficiently.
1. Opening a File
To open a file, we can use open() function, which requires file-path and mode as arguments.
Syntax:
file = open("filename", "mode")
# here,
# filename : name (or path) of the file to be opened.
# mode: mode in which you want to open the file (read, write, etc.).Example:
file = open("data.txt", "r")
# This code opens file data.txt in read mode.
# If the file exists, it returns a file object
# connected to that file; if the file does not exist,
# Python raises a FileNotFoundError.- If you don’t specify the mode, Python uses ‘r’ (read mode) by default.
— — — — — — — — — — — — — — — — — — -
2. Closing a File
The file.close() method closes the file and releases the system resources. If the file was opened in write or append mode, closing ensures that all changes are properly saved.
file = open("data.txt", "r")
file.close()— — — — — — — — — — — — — — — — — — -
3. Reading a File
Reading a file can be achieved by file.read() which reads the entire content of the file. After reading, it’s good practice to close the file to free up system resources.
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()read()– Read Entire File : Reads the full content as one string.
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()You can also read specific number of characters:
content = file.read(10) # Reads first 10 characters2. readline() – Read One Line : Reads one line at a time.
file = open("data.txt", "r")
line = file.readline()
print(line)
file.close()You can call it multiple times:
print(file.readline())
print(file.readline())3. readlines() – Read All Lines into a List : Returns a list of lines.
file = open("data.txt", "r")
lines = file.readlines()
print(lines)
file.close()
# output
# ['Line 1\n', 'Line 2\n', 'Line 3\n']Reading File Line by Line
Best for large files:
with open("data.txt", "r") as file:
for line in file:
print(line.strip())Why this is better?
- Memory efficient
- Reads one line at a time
Encoding While Opening File
Sometimes needed for Unicode text:
file = open("data.txt", "r", encoding="utf-8")Important when working with:
- Hindi / Gujarati text
- Special symbols
- International data
— — — — — — — — — — — — — — — — — — -
4. Writing a File
In Python, writing to a file is done using the mode “w”. This creates a new file if it doesn’t exist, or overwrites the existing file if it does. The write() method is used to add content. After writing, make sure to close the file.
with open("geek.txt", "w") as file:
file.write("Hello, Python!\n")
file.write("File handling is easy with Python.")
print("File written successfully")- “w” mode opens the file for writing (overwrites existing content if the file already exists).
- write() method adds new text to the file.
- When using with, the file closes automatically at the end of the block.
File Modes for Writing
writelines() : Writing Multiple Lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("data.txt", "w") as file:
file.writelines(lines)- writelines() does NOT add \n automatically.
- You must include newline manually.
Checking File Properties
Once the file is open, we can check some of its properties:
f = open("data.txt", "r")
print("Filename:", f.name)
print("Mode:", f.mode)
print("Is Closed?", f.closed)f.close()
print("Is Closed?", f.closed)- f.name: Returns the name of the file that was opened (in this case, “data.txt”).
- f.mode: Tells us the mode in which the file was opened. Here, it’s ‘r’ which means read mode.
- f.closed: Returns a boolean value- False when file is currently open otherwise True.
Using with Statement in Python
The with statement is the best and safest way to work with files in Python.
It automatically handles opening and closing of files.
syntax:
with open("filename", "mode") as variable:
# block of codeExample:
with open("data.txt", "r") as file:
content = file.read()
print(content)Why Use with
Without with:
file = open("data.txt", "r")
content = file.read()
file.close()Problems:
- If an error occurs before close(), file remains open
- Can cause memory leaks
- Bad practice in production
With with:
with open("data.txt", "r") as file:
content = file.read()- Automatically closes file
- Safer
- Cleaner
- Industry standard
Multiple Files in One with
with open("source.txt", "r") as source, open("dest.txt", "w") as dest:
data = source.read()
dest.write(data)- Both files close automatically
- Useful for file copying
Working with Binary Files in Python
Binary files store data in raw byte format, not readable text.
Get Saurabh Gandhi’s stories in your inbox
Join Medium for free to get updates from this writer.
Examples:
- Images (.jpg, .png)
- PDFs (.pdf)
- Videos (.mp4)
- Audio (.mp3)
- Executables (.exe)
Unlike text files, binary files are handled using binary mode (b).
1. Opening a Binary File
open("filename", "rb") # Read binary
open("filename", "wb") # Write binary
open("filename", "ab") # Append binary2. Reading a Binary File
with open("image.jpg", "rb") as file:
data = file.read()
print(data[:50]) # First 50 bytes3. Writing a Binary File
with open("image.jpg", "rb") as source:
data = source.read()
with open("copy.jpg", "wb") as dest:
dest.write(data)4. Reading Large Binary Files
with open("video.mp4", "rb") as file:
while True:
chunk = file.read(1024) # 1 KB chunk
if not chunk:
break
print(len(chunk))Buffering
When you open a file, Python does not read/write directly to disk every time.
Why buffering?
- Reduces disk I/O
- Improves speed
- Minimizes system calls
Control Buffering
open("data.txt", "r", buffering=1024) # 1KB bufferFile Pointer (seek() & tell())
tell()
- Returns current byte position.
seek(offset, whence)
Example:
with open("data.txt", "rb") as f:
f.seek(5)
print(f.read(10))Reverse Reading Example:
with open("data.txt", "rb") as f:
f.seek(-10, 2) # Last 10 bytes
print(f.read())seek() with negative offset works only in binary mode.
Handling Very Large Files
❌ Bad:
data = file.read() # Loads everything into memory✔ Good:
with open("bigfile.txt") as f:
for line in f:
process(line)✔ Even Better (Chunk Reading):
def read_in_chunks(file, chunk_size=1024):
while chunk := file.read(chunk_size):
yield chunk
with open("bigfile.txt") as f:
for chunk in read_in_chunks(f):
process(chunk)Asynchronous File Handling (Async I/O)
Useful in:
- Web servers
- High-concurrency apps
Using aiofiles:
import aiofiles
import asyncio
async def read_file():
async with aiofiles.open("data.txt", "r") as f:
content = await f.read()
print(content)
asyncio.run(read_file())Working with Compressed Files
Compressed files reduce file size and are commonly used for:
- Backups
- Data transfer
- Logs
- Large datasets
- Software distribution
Python provides built-in modules to work with compressed files directly without manually extracting them.
1. Working with ZIP Files (zipfile Module)
Python provides the built-in zipfile module.
- Creating a ZIP File
import zipfile
with zipfile.ZipFile("archive.zip", "w") as zipf:
zipf.write("data.txt")Creates archive.zip
Adds data.txt inside it
- Adding Multiple Files
import zipfile
with zipfile.ZipFile("archive.zip", "w") as zipf:
zipf.write("file1.txt")
zipf.write("file2.txt")- Extracting ZIP File
import zipfile
with zipfile.ZipFile("archive.zip", "r") as zipf:
zipf.extractall("extracted_folder")- Reading a File Inside ZIP (Without Extracting)
import zipfile
with zipfile.ZipFile("archive.zip", "r") as zipf:
with zipf.open("data.txt") as file:
print(file.read().decode("utf-8"))Very useful for large datasets
No need to manually unzip
— — — — — — — — — — — — — — — — —
2. Working with GZIP Files (gzip Module)
Used for .gz files (commonly for logs and large data).
- Writing GZIP File
import gzip
with gzip.open("data.txt.gz", "wt") as file:
file.write("Hello Compressed World")"wt" → Write Text
"wb" → Write Binary
- Reading GZIP File
import gzip
with gzip.open("data.txt.gz", "rt") as file:
print(file.read())Common in:
— Log compression
— Data pipelines
— Big data processing
— — — — — — — — — — — — — — — — —
3. Working with TAR Files (tarfile Module)
Used for .tar, .tar.gz, .tgz
- Creating TAR Archive
import tarfile
with tarfile.open("archive.tar", "w") as tar:
tar.add("data.txt")- Creating Compressed TAR (tar.gz)
import tarfile
with tarfile.open("archive.tar.gz", "w:gz") as tar:
tar.add("data.txt")- Extracting TAR
import tarfile
with tarfile.open("archive.tar.gz", "r:gz") as tar:
tar.extractall("output_folder")Questions
- What is file handling?
- Difference between w and a mode?
- What is with statement?
- Difference between read() and readlines()?
- What happens if file doesn’t exist in r mode?
- Explain file pointer.
- What is buffering?
- Difference between text and binary mode?
- Difference between ZIP and GZIP?
- What problem does
withsolve? - Can we open multiple files in one
with?









