Introduction: Why File Handling?
Chapter 7: Working with Files in Python – Introduction: Why File Handling?
What is File Handling?
File handling is the ability to read data from files and write data to files using a programming language. In Python, this means you can open a text file, read its contents into your program, process that data, and then save new data back to a file.
Why Do We Need File Handling?
So far in this course, all the data you have worked with—variables, lists, dictionaries—disappears when your program ends. If you want to keep information between runs (like a list of tasks, user settings, or a log of actions), you must store it in a file. File handling is the bridge between your program’s temporary memory and permanent storage on your computer.
In the real world, almost every application uses files:
- Configuration files store user preferences (e.g.,
settings.txt). - Data files hold records like a to-do list or inventory.
- Log files record errors or events for debugging.
- APIs often read from or write to files before sending data over the internet.
By the end of this course, you will build a Tasks API that saves tasks to a database. But before that, you need to understand how Python interacts with files—because databases are just a more advanced form of file handling.
How Python Handles Files
Python provides a built-in function called open() to work with files. The basic steps are:
- Open the file (specify the filename and the mode: read, write, append, etc.).
- Read or write data.
- Close the file to free up system resources.
The most common modes are:
'r'– Read (default). Opens a file for reading. Error if file does not exist.'w'– Write. Creates a new file or overwrites an existing one.'a'– Append. Adds data to the end of an existing file, or creates a new file if it doesn’t exist.'r+'– Read and write (does not truncate the file).
Practical Example: Reading a File
Let’s create a simple text file named tasks.txt with the following content:
Buy groceries
Finish homework
Call mom
Now, write a Python script to read and display each line:
# Open the file in read mode
file = open('tasks.txt', 'r')
# Read all lines into a list
lines = file.readlines()
# Close the file
file.close()
# Print each line
for line in lines:
print(line.strip()) # strip() removes the newline character
Output:
Buy groceries
Finish homework
Call mom
Notice that we always close the file after we are done. Forgetting to close can cause data loss or memory issues.
Using the with Statement (Best Practice)
Python offers a cleaner way to handle files using the with statement. It automatically closes the file for you, even if an error occurs.
# Using 'with' to read a file
with open('tasks.txt', 'r') as file:
content = file.read()
print(content)
This is the recommended approach for all file operations.
Writing to a File
To write data, use mode 'w' (careful: this overwrites the file).
new_task = "Practice Python"
with open('tasks.txt', 'w') as file:
file.write(new_task + '\n')
After running this, tasks.txt will contain only Practice Python. The old tasks are gone.
Appending to a File
To add data without deleting existing content, use mode 'a'.
another_task = "Read a book"
with open('tasks.txt', 'a') as file:
file.write(another_task + '\n')
Now the file contains:
Practice Python
Read a book
Common Beginner Mistakes
- Forgetting to close the file – Always use
withto avoid this. - Using wrong mode – Opening a file in
'w'when you meant'a'will erase your data. - Not handling missing files – Trying to read a file that doesn’t exist raises a
FileNotFoundError. We will cover error handling in the next lesson. - Forgetting newline characters – When writing multiple lines, add
'\n'explicitly, or usewritelines()with a list.
Practical Task for This Chapter
Create a Python script that does the following:
- Opens a file named
journal.txtin append mode. - Asks the user to enter a sentence (their journal entry for today).
- Writes that sentence to the file, each on a new line.
- After writing, reads the entire file and prints it to the console.
Hint: You will need to open the file twice: once for appending, and once for reading. Or you can open it in 'a+' mode (append and read) and use file.seek(0) to go back to the beginning before reading.
Try it yourself before looking at the solution below.
# Get user input
entry = input("Enter your journal entry: ")
# Append to file
with open('journal.txt', 'a') as file:
file.write(entry + '\n')
# Read and display all entries
with open('journal.txt', 'r') as file:
print("\nYour journal so far:")
print(file.read())
What’s Next?
In the next lesson, we will learn how to handle errors that occur when working with files (like missing files or permission issues). This is a critical skill for building robust applications.
Loading ratings...