- Home
- /
- Python File Handling
Python Tutorial
Introduction
Python Data Types & Oper...
Python Strings
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Python Loops
Python Functions
Python Modules
Python OOPS
Advanced Topics
File Handling
- Home
- /
- Python File Handling
Python File Handling
Python gives you the ability to interact with files directly—this means you can read from, write to, or update files stored on your system.
Before doing anything with a file, we must first open it using Python’s built-in open()
function.
Opening and Reading a File
Let’s assume there’s a text file named info.txt
in the same folder as your Python script.
file = open("info.txt")
print(file.read())
Output:
This is some sample content inside the file.
It was written just to test reading from a file in Python.
This example shows how you can load and read the entire contents of a file.
File Modes
You can open a file in different modes, depending on what you want to do with it:
Mode | Purpose |
---|---|
'r' | Read-only mode (default). Error if the file doesn’t exist. |
'w' | Write-only mode. Overwrites if file exists, creates new if not. |
'a' | Append mode. Adds to the end of the file if it exists. |
'x' | Create mode. Creates a new file, error if it already exists. |
You can also specify how you want to handle the file content:
't'
= Text mode (default for plain files)'b'
= Binary mode (used for images, PDFs, etc.)
Examples
1. Reading a File
file = open("data.txt", "r")
print(file.read())
file.close()
This opens the file data.txt
in read mode and prints its contents.
2. Writing to a File (Overwrites)
file = open("data.txt", "w")
file.write("This content replaces whatever was there before.")
file.close()
If the file already exists, its content will be erased and replaced.
3. Appending to a File
file = open("data.txt", "a")
file.write("\nThis line gets added to the end.")
file.close()
New content is added to the file without deleting the old content.
4. Creating a New File
file = open("new_file.txt", "x")
file.write("This file was created using create mode.")
file.close()
If new_file.txt
already exists, this code will throw an error.
Quick Tips
Always close a file after you’re done using it with
file.close()
.Or better: use the
with
statement—it automatically handles closing the file.
with open("info.txt", "r") as file:
content = file.read()
print(content)
Summary
Use
open(filename, mode)
to open a file.Read files using
.read()
, write with.write()
, and append with.a
.Always close files or use
with
for automatic cleanup.Make sure the file you’re trying to open exists—or handle it with error checking.