Python Introduction to Files
Table of Contents
In the last lesson, we learned about Python Custom Exceptions. Now letโs learn how Python programs can save information and work with files.
What Is File Handling in Python?
File handling means working with files on our computer. We can create files, read from them, write to them, and append to them.
Python makes this very easy. It has built-in functions for file operations. No extra libraries needed.
Why Do We Need File Handling in Python?
So far, all our programs have been temporary. We run them. They do something. Then they stop. And everything is gone.
If we want to keep data, we need to save it somewhere. That is where files come in.
Files are everywhere. Configuration files. Log files. Data files. Reports. If we want our program to remember something, we save it to a file.
How to Open a File in Python
To work with a file, we first need to open it. We use the open() function.
file = open("example.txt", "r")That opens the file example.txt in read mode. The "r" means read.
The open() function returns a file object. We use that object to read or write.
File Modes in Python
The mode tells Python what we want to do with the file. Here are the common modes.
| Mode | Meaning |
|---|---|
"r" | Read. Opens for reading. Error if file does not exist. |
"w" | Write. Opens for writing. Creates file if not exists. Erases contents if exists. |
"a" | Append. Opens for writing. Creates file if not exists. Adds to the end. |
"x" | Create. Creates a new file. Error if file already exists. |
"b" | Binary mode. Use with others like "rb" or "wb". |
"t" | Text mode. Default. Use with others like "rt" or "wt". |
We can combine them. Like "rb" for read binary. Or "w+" for read and write.
For now, we will focus on text mode.
How to Read a File in Python
Once we open a file in read mode, we can read its contents.
file = open("example.txt", "r")content = file.read()print(content)file.close()The read() method reads the entire file and returns it as a string.
We can also read one line at a time.
file = open("example.txt", "r")line = file.readline()while line: print(line) line = file.readline()file.close()Or read all lines into a list.
file = open("example.txt", "r")lines = file.readlines()for line in lines: print(line)file.close()How to Write to a File in Python
To write to a file, we open it in write mode.
file = open("output.txt", "w")file.write("Hello, world!\n")file.write("This is a new line.\n")file.close()We need to be careful. Write mode "w" erases the existing content. So if we want to keep the old content and add to it, we use append mode "a".
file = open("output.txt", "a")file.write("This line is added.\n")file.close()How to Close a File in Python
We should always close a file when we are done with it. It frees up resources. And it makes sure all data is written to disk.
file.close()If we forget to close, the file might stay locked. And data might not be saved.
Using with Statement in Python File Handling
Closing files manually is error-prone. If an exception happens, we might never reach the close() line. That is why Python has the with statement.
with open("example.txt", "r") as file: content = file.read() print(content)The with statement automatically closes the file when the block ends. Even if an exception happens. So we do not need to call close().
That is the recommended way to work with files.
with open("output.txt", "w") as file: file.write("Hello, world!\n")Python File Handling Example
Letโs write a simple program that writes a shopping list to a file and then reads it back.
# Write to filewith open("shopping.txt", "w") as file: file.write("apples\n") file.write("bananas\n") file.write("oranges\n")
# Read from filewith open("shopping.txt", "r") as file: content = file.read() print(content)Output
applesbananasorangesThat is a simple way to save and load data.
Appending to a Log File in Python
import datetime
def log_message(message): timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") with open("log.txt", "a") as file: file.write(f"{timestamp} - {message}\n")
log_message("Program started")log_message("User logged in")log_message("Program ended")That appends a timestamped message to a log file. Each time we run it, new lines are added.
Common File Handling Mistakes in Python
Mistake 1: Forgetting to close the file
file = open("data.txt", "r")content = file.read()# forgot to closeFix: Use with or remember to call close().
Mistake 2: Using write mode when we meant append
with open("data.txt", "w") as file: file.write("New data")This erases the file. If we wanted to add to the end, we use "a".
Mistake 3: Trying to read a file that does not exist
with open("missing.txt", "r") as file: content = file.read()This raises a FileNotFoundError. We handle it with a try-except.
try: with open("missing.txt", "r") as file: content = file.read()except FileNotFoundError: print("File not found")Mistake 4: Forgetting the newline character
file.write("Hello")file.write("World")Output in file:
Output
HelloWorldFix: Add \n if we want each on a new line.
file.write("Hello\n")file.write("World\n")Next, we will learn about Python Reading Files and read complete files or individual lines safely.