Chapter 8: File Handling in Python
Learn to work with files in Python, including reading from and writing to files, for data persistence and management.
In this chapter, we�ll explore file handling in Python, including opening, reading, writing, and closing files. Working with files allows you to store data permanently and retrieve it when needed, making it essential for data persistence.
Opening and Closing Files
To work with files in Python, you first need to open them using the open()
function. After performing file operations, always close the file to free up system resources:
file = open("example.txt", "r") # Open file in read mode
# Perform file operations here
file.close() # Close the file
In this example, we opened a file in read mode and then closed it after performing operations.
Reading Files
Python provides several methods for reading files, including read()
, readline()
, and readlines()
:
read()
: Reads the entire content of the file.readline()
: Reads one line at a time.readlines()
: Reads all lines and returns a list of lines.
file = open("example.txt", "r")
content = file.read() # Reads entire file content
print(content)
file.close()
In this example, read()
reads the entire content of the file, which is then printed to the console.
Writing to Files
To write data to a file, open it in write mode ("w")
or append mode ("a")
. Write mode overwrites existing content, while append mode adds to the end of the file:
file = open("example.txt", "w")
file.write("Hello, world!")
file.close()
Here, write()
is used to add text to the file. Opening the file in write mode will overwrite any existing content.
Using with
for File Handling
Python provides a convenient way to work with files using the with
statement, which automatically closes the file after the block of code is executed:
with open("example.txt", "r") as file:
content = file.read()
print(content)
This approach is preferred because it ensures the file is properly closed even if an error occurs.
Appending Data to Files
To add data to the end of an existing file without overwriting it, open the file in append mode ("a")
:
with open("example.txt", "a") as file:
file.write("\nAdding a new line!")
This code adds a new line to the end of the file without altering its existing content.
File Modes
When opening files, different modes are available to control read and write permissions:
"r"
: Read-only mode (default)."w"
: Write mode (overwrites content)."a"
: Append mode (adds to end of file)."r+"
: Read and write mode."b"
: Binary mode (e.g.,"rb"
for read binary).
Summary and Next Steps
In this chapter, we covered the basics of file handling in Python, including reading and writing files. Using files allows your programs to persist data and retrieve it when needed. In the next chapter, we�ll explore error handling and learn how to manage exceptions in your code.