Basic File I/O in Python
Learning to work with files is one of the most practical skills you can pick up as a beginner Python programmer. Whether you want to save your notes, read…
Learning to work with files is one of the most practical skills you can pick up as a beginner Python programmer. Whether you want to save your notes, read a list of tasks, or process data for a future job, file operations are everywhere. In this tutorial, you’ll discover how to open, read, and write files in Python—step by step.
What Is File I/O?
File I/O stands for "File Input/Output." It’s a technical way of saying “reading from or writing to files on your computer.”
Why does this matter? Most programs need to work with data that lives outside the code itself. For example:
- Saving your game progress
- Loading a list of names from a text file
- Writing a log of your program’s activity
These are all file operations. Understanding Python file I/O will help you build programs that can remember things, process real-world data, and interact with other tools.
Types of Files You Can Work With
Files come in many shapes and sizes, but as a beginner, you’ll mostly work with two types:
- Text files: Store data as readable text (like
.txtor.csvfiles) - Binary files: Store data in a format meant for computers, not humans (like images or audio files)
For now, we’ll focus on text files. They’re the easiest to start with and cover most beginner needs.
Some common text file types you might see:
.txt— Plain text files (notes, lists, etc.).csv— Comma-separated values, often used for spreadsheets or simple databases
Opening Files in Python
To work with a file, you must first open it. Python gives you a built-in function called open() for this purpose.
The basic way to open a file looks like this:
file = open("example.txt", "r")
Here’s what’s happening:
"example.txt"is the name of the file you want to open."r"tells Python you want to read the file.
There are several modes you can use with open():
"r"— Read (default): Opens the file for reading."w"— Write: Opens the file for writing (and erases existing content)."a"— Append: Opens the file for writing, but keeps existing content and adds new data to the end.
When you open a file, Python gives you a file object. You use this object to read or write data.
Quiz Question 1
Question: Which mode should you use with open() if you want to add new content to the end of a file without erasing its existing content?
- A) 'r'
- B) 'w'
- C) 'a'
Reading from a File
Let’s start by reading data from a file. Suppose you have a file called notes.txt with some text inside.
Reading the Entire File
You can read the whole file at once using the .read() method:
file = open("notes.txt", "r")
content = file.read()
print(content)
file.close()
This prints everything in notes.txt to the screen.
Reading Line by Line
Often, you’ll want to process a file one line at a time. You can do this with a loop:
file = open("notes.txt", "r")
for line in file:
print(line.strip())
file.close()
The .strip() method removes any extra spaces or line breaks.
Reading Only the First Line
If you want to read just the first line of a file, you can use the .readline() method:
file = open("notes.txt", "r")
first_line = file.readline()
print(first_line.strip())
file.close()
Writing to a File
Now let’s write data to a file. This is how you can save information for later use.
Writing (Overwriting) a File
To write to a file, open it in "w" mode. Warning: This will erase any existing content in the file.
file = open("output.txt", "w")
file.write("Hello, world!\n")
file.write("This is my first file.\n")
file.close()
After running this, output.txt will contain your two lines of text.
Appending to a File
If you want to add new content without erasing what’s already there, use "a" mode:
file = open("output.txt", "a")
file.write("Adding another line.\n")
file.close()
Now output.txt keeps the old content and adds your new line at the end.
Quiz Question 2
Question: What's the difference between 'w' and 'a' modes when opening a file in Python?
- A) 'w' overwrites the file, 'a' appends to it
- B) 'w' reads the file, 'a' writes to it
- C) 'w' is for text files, 'a' is for binary files
Closing Files and Why It Matters
Whenever you open a file, it’s important to close it when you’re done. This frees up resources and makes sure your data is saved properly.
You can close a file using:
file.close()
But there’s an even safer (and easier) way: the with statement. This automatically closes the file for you, even if something goes wrong.
with open("notes.txt", "r") as file:
content = file.read()
print(content)
# File is now closed automatically
Using with is the recommended way for most file operations in Python.
Quiz Question 3
Question: Why is it recommended to use the 'with' statement when working with files in Python?
- A) It automatically closes the file for you
- B) It makes your code run faster
- C) It lets you open multiple files at once
- D) It prevents you from writing to the file
Common File I/O Errors and How to Avoid Them
Working with files isn’t always smooth sailing. Here are some common issues beginners face—and how to handle them.
File Not Found
If you try to open a file that doesn’t exist, Python will give you an error:
with open("missing.txt", "r") as file:
content = file.read()
How to avoid: Make sure the file exists in the same folder as your Python script, or provide the correct path.
Permission Errors
Sometimes, you might not have permission to read or write a file (especially on shared or protected computers).
How to avoid: Make sure you have the right permissions, and try running your script in a folder where you have access.
Checking If a File Exists
If you’re not sure if a file exists, you can check first using Python’s os.path.exists() function:
import os
if os.path.exists("notes.txt"):
with open("notes.txt", "r") as file:
print(file.read())
else:
print("File not found.")
Quiz Question 4
Question: What happens if you try to open a file for reading ('r') and the file does not exist?
- A) Python creates a new empty file
- B) Python gives a "FileNotFoundError"
- C) Python ignores the error and continues
Practice: Simple File I/O Exercises
The best way to learn is by doing! Here are a few simple exercises to try on your own.
-
Read a File:
Create a text file calledmydata.txtwith a few lines of text. Write a Python script that reads and prints each line. -
Write to a File:
Write a script that asks the user for their name and saves it to a file callednames.txt. -
Append Data:
Modify your script to add a new name tonames.txteach time you run it, instead of overwriting the file. -
Test Safely:
If you’re worried about overwriting important files, practice with new files or use files with “test” in the name.
Wrapping Up
You’ve just learned the basics of Python file I/O: how to open, read, and write files. These skills are the foundation for many real-world programming tasks, from data analysis to web development.
Keep practicing with your own files. The more you experiment, the more confident you’ll become. Soon, reading and writing files in Python will feel like second nature!
Quiz Answer Key
Question 1
Correct answer: C) 'a'
Explanation: The 'a' mode stands for append, which adds new data to the end of the file without deleting what's already there.
Question 2
Correct answer: A) 'w' overwrites the file, 'a' appends to it
Explanation: 'w' mode erases the file's existing content before writing, while 'a' mode keeps the existing content and adds new data to the end.
Question 3
Correct answer: A) It automatically closes the file for you
Explanation: The 'with' statement ensures that the file is properly closed after you're done, even if an error occurs.
Question 4
Correct answer: B) Python gives a "FileNotFoundError"
Explanation: If you try to open a file for reading and it doesn't exist, Python will raise a FileNotFoundError.