Python File Handling
Safely read from and write to files.
Many Python programs need to work with files. You may want to save user information, read data from a text file, store application settings, or generate reports. Instead of keeping data only in memory while a program runs, files let you save information permanently so it can be used again later.
Python makes file handling simple with built-in functions that let you create, read, write, and update files.
In this lesson, you will learn the basics of file handling, different file modes, how to read and write files, and best practices for working safely with files.
What is File Handling?
File handling is the process of creating, opening, reading, writing, and closing files. Python can work with many file types.
- Text files (.txt)
- CSV files (.csv)
- JSON files (.json)
- Log files (.log)
- Python files (.py)
For beginners, text files are the easiest place to start.
Opening a File
Python uses the built-in open() function to open a file.
Syntax
open(filename, mode)The filename identifies the file to open, and the mode tells Python what you want to do with it.
Example
file = open("notes.txt", "r")This opens notes.txt in read mode.
File Modes
Python supports different file modes depending on the operation you want to perform.
| Mode | Description |
|---|---|
| r | Read a file; this is the default mode |
| w | Write to a file; creates a new file or overwrites an existing one |
| a | Append data to the end of a file |
| x | Create a new file; fails if the file already exists |
| rb | Read a binary file |
| wb | Write a binary file |
Choosing the correct mode is important because some modes can replace existing file contents.
Reading a File
The read() method reads the entire contents of a file.
file = open("notes.txt", "r")
content = file.read()
print(content)
file.close()The close() method releases the file after use.
Reading One Line at a Time
The readline() method reads the next line from the file each time it is called.
file = open("notes.txt", "r")
print(file.readline())
file.close()Reading All Lines
The readlines() method returns all lines as a list. This is useful when you want to process lines separately.
file = open("notes.txt", "r")
lines = file.readlines()
print(lines)
file.close()Writing to a File
The w mode writes data to a file. If the file already exists, its previous contents are replaced, so use this mode carefully to avoid losing important data.
file = open("notes.txt", "w")
file.write("Welcome to DevBrainBox!")
file.close()Appending Data
To keep existing content and add new data at the end, use append mode (a).
file = open("notes.txt", "a")
file.write("
Python is easy to learn.")
file.close()The new text is added without removing the previous content.
Using the with Statement
The recommended way to work with files is the with statement. It automatically closes the file after the block finishes, even if an error occurs.
with open("notes.txt", "r") as file:
content = file.read()
print(content)This approach makes your code cleaner and safer.
Working with CSV Files
CSV (Comma-Separated Values) files are commonly used to store table-like data.
Name,Age
Alice,22
John,25Python provides the built-in csv module to read and write CSV files efficiently.
Working with JSON Files
JSON (JavaScript Object Notation) is a popular format for storing and exchanging structured data.
{
"name": "Alice",
"age": 22
}Python's built-in json module converts between Python objects and JSON data. JSON is widely used with web applications and APIs.
Checking if a File Exists
Before opening a file, it is often helpful to check whether it exists.
import os
if os.path.exists("notes.txt"):
print("File found.")
else:
print("File does not exist.")This can prevent errors when attempting to open missing files.
Common File Handling Errors
- Opening a file that does not exist
- Forgetting to close a file
- Using the wrong file mode
- Overwriting important data by mistake
- Using an incorrect file path
Using the with statement and checking whether a file exists can help avoid many of these problems.
Best Practices
- Use meaningful file names.
- Prefer the with statement instead of manually closing files.
- Choose the correct file mode for your task.
- Specify an appropriate text encoding, such as UTF-8, when portability matters.
- Keep backups of important files before overwriting them.
- Handle errors gracefully using exception handling when opening files.
These habits help you write safer and more reliable programs.
Key Takeaways
- File handling allows Python programs to read, write, and manage files.
- The open() function opens files.
- Modes such as r, w, a, and x determine how a file is accessed.
- Use read(), readline(), and readlines() to read file contents.
- Use write mode to create or overwrite files and append mode to add data.
- The with statement automatically closes files and is the recommended approach.
- Python provides built-in modules for working with CSV and JSON files.
- Use the os module to check whether a file exists before opening it.
- Choosing the correct file mode and handling errors carefully helps prevent data loss.
- File handling is essential for applications that store and manage persistent data.