Advertisement
Working with files is one of those things in programming that doesn’t get much attention until you need it. Whether it’s reading a config, saving user input, or logging events, file handling is everywhere. Python makes it easy, almost too easy. No setup, no external tools—just a few built-in functions that quietly do the job.
That simplicity hides how useful it really is. If you’re learning Python or building something real, knowing how to read, write, and manage files is a skill you’ll use more often than you think. This guide walks through file handling in Python with real examples.
Python uses the built-in open() function to work with files. This function takes the filename and mode as arguments. The most common modes are 'r' (read), 'w' (write), and 'a' (append).
file = open('example.txt', 'r') # Open for reading
data = file.read()
file.close()
You must close a file when you're done with it. If you forget, it can cause issues like memory leaks or file locks. A better way is to use the with statement, which handles closing automatically.
with open('example.txt', 'r') as file:
data = file.read()
The with block keeps it clean and safe.
To write to a file, use 'w' or 'a'. 'w' creates a new file or overwrites an existing one. 'a' appends to the end without deleting content.
with open('output.txt', 'w') as file:
file.write('Hello, Python!\n')
file.write('Second line.')
Each write() call adds text to the file. If you want a new line, include \n.
If you don’t want to erase existing data:
with open('output.txt', 'a') as file:
file.write('Appended line.\n')
This way, nothing gets lost.
Reading a big file all at once isn’t ideal. For large files, read one line at a time using a loop.
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
strip() removes the newline at the end. This method is memory-efficient and clear.
Or, use readline():
with open('example.txt', 'r') as file:
line = file.readline()
while line:
print(line.strip())
line = file.readline()
Both give you more control if needed.
If you want to grab the whole file at once but keep each line separate, use readlines():
with open('example.txt', 'r') as file:
lines = file.readlines()
print(lines)
This gives you a list where each item is a line from the file. It’s useful for quick lookups or filtering.
There are several modes you can use with open():
Example of binary mode:
with open('image.jpg', 'rb') as file:
data = file.read()
Use binary mode for files that aren’t plain text like images, PDFs, or audio files.
If you’re writing more than one line, writelines() can help.
lines = ['First line\n', 'Second line\n', 'Third line\n']
with open('output.txt', 'w') as file:
file.writelines(lines)
Make sure each line ends with \n, or it’ll all run together. This method is cleaner when working with lists.
Before opening a file, you may want to check if it exists. Python’s os module handles that.
import os
if os.path.exists('example.txt'):
with open('example.txt', 'r') as file:
print(file.read())
else:
print('File not found.')
You can also use os.path.isfile() if you want to make sure it’s not a folder.
Use the os module to manage files beyond reading and writing.
To delete a file:
import os
if os.path.exists('output.txt'):
os.remove('output.txt')
To rename a file:
os.rename('oldname.txt', 'newname.txt')
These functions are useful in cleanup scripts or when handling temporary files.
Sometimes, you need to store structured data. Instead of creating your format, you can use JSON. It's readable, works well with Python dictionaries, and is easy to write and load.
Python’s json module makes this smooth:
import json
data = {'name': 'Alice', 'age': 25}
# Writing JSON to file
with open('data.json', 'w') as file:
json.dump(data, file)
To read that data back:
with open('data.json', 'r') as file:
loaded_data = json.load(file)
print(loaded_data)
JSON is useful when working with APIs or saving settings. It keeps your data clean and organized.
Things can go wrong when handling files. Maybe the file doesn’t exist, or permissions are off. Instead of letting your program crash, you can use try and except to manage errors.
try:
with open('missing.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print('The file was not found.')
except PermissionError:
print('Permission denied.')
except Exception as e:
print(f'An unexpected error occurred: {e}')
This keeps your code safe and user-friendly. It’s especially useful when working with input from users or external systems where you can’t be sure what’s there.
Sometimes, you don’t want to read a file from start to finish. You might need to jump to a specific position or track where you are in the file. That’s where seek() and tell() come in.
seek() moves the file pointer to a specific byte position. tell() shows the current position.
with open('example.txt', 'r') as file:
print(file.read(5)) # Reads first 5 characters
position = file.tell() # Gets current position
print(f'Current position: {position}')
file.seek(0) # Moves pointer back to the beginning
print(file.read(5)) # Reads the first 5 characters again
This is useful when you’re dealing with large files or binary data, and you want precise control over where to read or write. It also helps when you need to rewind and reprocess part of a file without reopening it.
File handling in Python is simple once you know the basics. Whether you're reading, writing, or managing files, the built-in tools cover almost everything you’ll need. Using the right method for each task helps you keep your code clean and efficient. With just a few lines, you can create logs, store data, or process input with ease. The more you use these tools, the more natural they’ll feel. Python’s approach to files is direct, reliable, and easy to remember.
Advertisement
Automation Anywhere boosts RPA with generative AI, offering intelligent automation tools for smarter and faster workflows
Learn how to track real-time AI ROI, measure performance instantly, save costs, and make smarter business decisions every day
Learn the basics and best practices for updating file permissions in Linux with chmod. Understand numeric and symbolic modes, use cases, and safe command usage
Discover Nvidia’s latest AI Enterprise Suite updates, featuring faster deployment, cloud support, advanced AI tools, and more
Learn how to list files in a directory using Python with clear and practical methods. Covering os, glob, and pathlib, this guide is all you need to get started
Discover how Lucidworks’ new AI-powered platform transforms enterprise search with smarter, faster, and more accurate results
Discover how AI adoption is evolving in 2025, including critical shifts, business risks, and future growth opportunities.
Know about 5 powerful AI tools that boost LinkedIn growth, enhance engagement, and help you build a strong professional presence
Explore CodeGemma, Google's latest AI model designed for developers. This open-source tool brings flexibility, speed, and accuracy to coding tasks using advanced code LLMs
Microsoft’s new AI model Muse revolutionizes video game creation by generating gameplay and visuals, empowering developers like never before
LeMaterial is an open source platform designed to accelerate materials discovery through shared tools, data, and machine learning workflows. Discover how it’s reshaping collaboration in materials research
Meta's new AI boosts computer vision tools' speed, accuracy, and ethics across healthcare, retail, and real-time visual systems