Select a Subtopic
Day 6: File Handling
Topics
- Reading and Writing Files in Python
- File Modes
- File Handling Exceptions
Reading Files
In Python, you can read from a file using the built-in open()
function with the r
mode (read mode).
# Open the file in read mode
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
Writing to Files
To write data to a file, you use the open()
function with the w
(write) or a
(append) mode.
# Open the file in write mode (it will overwrite existing content)
file = open('example.txt', 'w')
file.write("Hello, world!")
file.close()
# Open the file in append mode
file = open('example.txt', 'a')
file.write("\nAppended text.")
file.close()
File Modes
'r'
: Read (default mode)'w'
: Write (creates or overwrites the file)'a'
: Append (adds content to the file without overwriting)'b'
: Binary mode (used for non-text files like images)'x'
: Exclusive creation (creates a new file, returns an error if the file exists)
File Handling Exceptions
When working with files, it’s a good idea to handle potential errors (e.g., file not found) using try-except
blocks.
try:
file = open('nonexistent_file.txt', 'r')
content = file.read()
print(content)
except FileNotFoundError:
print("The file does not exist.")
finally:
if file:
file.close()
Exercises for Day 6
Exercise 1: Count the Number of Words in a File
Write a program that:
- Opens a text file.
- Reads the file and counts the number of words in it.
def count_words_in_file(file_name):
with open(file_name, 'r') as file:
content = file.read()
words = content.split()
return len(words)
print(count_words_in_file('example.txt'))
Exercise 2: Log Errors to a File
Write a program that:
- Creates a log file.
- Logs error messages with timestamps whenever an error occurs.
import datetime
def log_error(message):
with open('error_log.txt', 'a') as log_file:
log_file.write(f"{datetime.datetime.now()}: {message}\n")
log_error("File not found error")
log_error("Division by zero error")
Real-World Application
Now that you have an overview of **File Handling**, here's how you can implement this day’s learnings in a real-world project. You can start working with text-based files to store data, logs, or configuration settings, as well as improve your error-handling skills for robust code.