Python File Handling
Welcome to Python File Handling at Ugenz Academy!
File handling allows Python programs to store information in files and retrieve it later. Instead of losing data when a program finishes, you can save text, records, and other information for future use.
Python provides built-in functions and methods for working with files.
What You Will Learn
- Opening Files: Open files using the
open()function. - Reading Files: Read existing file contents.
- Writing Files: Create files or replace their contents.
- Appending Data: Add new information without removing existing content.
- Closing Files: Release file resources safely.
- Using
with: Automatically close files after operations. - Handling Errors: Manage missing files and other file-related exceptions.
File Opening Modes
| Mode | Purpose |
|---|---|
r | Read an existing file |
w | Write to a file, replacing existing content |
a | Append content to a file |
x | Create a new file; fail if it already exists |
rb | Read a file in binary mode |
wb | Write a file in binary mode |
Important: Opening a file with w can erase its existing contents.
Example: Writing to a File
with open("example.txt", "w", encoding="utf-8") as file: file.write("Welcome to Python File Handling!")
This creates example.txt if it doesn't exist or replaces its contents if it does.
Example: Reading a File
with open("example.txt", "r", encoding="utf-8") as file: content = file.read() print(content)
Output:
Welcome to Python File Handling!
The with statement automatically closes the file when the block finishes.
Example: Appending Data
with open("example.txt", "a", encoding="utf-8") as file: file.write("\nLearning Python is fun!")
This adds a new line without replacing the existing text.
Example: Handling a Missing File
try: with open("notes.txt", "r", encoding="utf-8") as file: print(file.read()) except FileNotFoundError: print("The requested file was not found.")
If notes.txt doesn't exist, the program displays a message instead of stopping with an unhandled error.
Why Is File Handling Important?
File handling is useful for saving application settings, maintaining logs, reading configuration files, storing records, and processing data. It is commonly used in automation, web development, and cybersecurity tools.
Recommended Learning Path
- Learn the
open()function and file modes. - Practice reading file contents.
- Create and write to files.
- Append information to existing files.
- Use
withto manage files safely. - Handle errors such as
FileNotFoundError.
Practice Challenge
Create a simple notes program that lets users enter a note, save it to notes.txt, and read all saved notes when requested.
Next step: Practice reading and writing files, then learn how exception handling makes your programs more reliable.
Learn • Build • Grow — Ugenz Academy