File Handling
File handling is a critical part of programming that involves reading from and writing to files. It's how programs persist data. Here's a comprehensive way to teach file handling in Python:
Reading from and Writing to Files
Python provides built-in functions for reading and writing to files.
Writing to a File
# Writing to a file
with open('example.txt', 'w') as file:
file.write("Hello, World!")
Reading from a File
# Reading from a file
with open('example.txt', 'r') as file:
content = file.read()
print(content)
Working with Different File Types
Python can work with various file types, including text, binary, JSON, and CSV files.
File Context Managers (with statement)
The with statement in Python is used for exception handling and automatically closes the file when the block is exited. This is considered best practice when working with files.
Using a Context Manager to Open a File
# Using a context manager to open a file
with open('example.txt', 'r') as file:
for line in file:
print(line, end='')