Lesson 6.1: Reading and Writing Files
Introduction:
File handling is essential in Python to store and retrieve data from external files. This lesson covers how to read from and write to files efficiently, which is crucial for data storage, reporting, and processing.
1. Opening a File:
-
Use the
open()function to open a file. -
Syntax:
Common File Modes:
| Mode | Description |
|---|---|
'r' |
Read (default) |
'w' |
Write (creates new file or overwrites) |
'a' |
Append (add content to end) |
'rb' |
Read binary |
'wb' |
Write binary |
2. Reading Files:
-
read()– Reads entire file content -
readline()– Reads one line at a time -
readlines()– Reads all lines into a list
Example:
3. Writing to Files:
-
write()– Writes string to file -
writelines()– Writes a list of strings
Example:
4. Using with Statement (Context Manager):
-
Automatically closes the file after block execution
Practical Tips:
-
Always close files to free resources (use
withto avoid manual closing) -
Choose correct file mode to avoid overwriting important data
-
Use
try-except(next lesson) to handle file errors safely
Learning Outcome of This Lesson:
-
Open, read, and write files using Python
-
Work with different file modes (
r,w,a) -
Use context managers for safer file handling
-
Prepare for exception handling in file operations
