Chapter 8: File Handling
File handling in Python allows you to create, read, update, and delete files. It is an essential skill for processing data stored in files such as text files, CSV files, and more.
Opening and Closing Files
To work with a file, you first need to open it. Python provides the open()
function to do so. After completing file operations, you should always close the file to release system resources.
Syntax:
File Modes:
Mode
Description
r
Read (default). Opens the file for reading. Raises an error if the file does not exist.
w
Write. Creates a new file or overwrites an existing file.
a
Append. Adds content to the end of the file.
x
Create. Creates a new file. Raises an error if the file already exists.
t
Text mode (default).
b
Binary mode.
Example:
Using with
Statement:
The with
statement is the preferred way to work with files as it automatically closes the file after the block of code is executed.
Reading Files
Python provides several methods to read files:
Method
Description
read()
Reads the entire content of the file as a string.
readline()
Reads one line at a time.
readlines()
Reads all lines and returns a list.
Example:
Writing to Files
To write content to a file, open it in write (w
) or append (a
) mode. Writing in w
mode overwrites existing content, while a
mode adds to the end.
Example:
Working with Binary Files
Binary files store data in a non-human-readable format, such as images or videos. Use binary mode (b
) to work with these files.
Example:
File Position and Methods
The file object provides methods to control the file position:
Method
Description
seek(offset)
Moves the cursor to a specific position.
tell()
Returns the current position of the cursor.
Example:
Checking File Existence
Use the os
module to check if a file exists before performing operations.
Example:
Handling Exceptions
Use try...except
blocks to handle errors gracefully when working with files.
Example:
Exercises
Exercise 1:
Write a program to read a file and count the number of lines, words, and characters.
Solution:
Exercise 2:
Write a program to copy content from one file to another.
Solution:
Exercise 3:
Write a program to read a binary file and display its contents in hexadecimal format.
Solution:
Best Practices
Always use the
with
statement to manage files.Handle exceptions to avoid crashes during file operations.
Use descriptive names for files and variables.
Check if a file exists before performing operations.
Use appropriate file modes to avoid unintended data loss.
In the next chapter, we will explore error and exception handling in greater depth, focusing on best practices for managing runtime errors in Python.
Last updated