Lesson 20: Python File Handling and Advanced I/O | Coding Class Series
Lesson 20: Python File Handling and Advanced I/O | Coding Class Series
Introduction
Welcome to Lesson 20!
In this lesson, we will learn file handling in Python, including reading, writing, appending, and advanced I/O operations.
File handling is essential to store and retrieve data for programs.
1. Opening a File
Python uses the open() function to work with files.
Syntax:
file = open("filename.txt", "mode")
Modes:
"r"– Read (default)"w"– Write (creates new file or overwrites)"a"– Append (adds content at the end)"r+"– Read and Write
Example:
file = open("sample.txt", "w")
file.write("Hello, World!")
file.close()
2. Reading from a File
file = open("sample.txt", "r")
content = file.read()
print(content)
file.close()
Other reading methods:
readline()– reads one line at a timereadlines()– reads all lines into a list
file = open("sample.txt", "r")
print(file.readline())
print(file.readlines())
file.close()
3. Writing and Appending
- Writing overwrites the file:
file = open("sample.txt", "w")
file.write("New content here.")
file.close()
- Appending adds data to the end:
file = open("sample.txt", "a")
file.write("\nThis line is appended.")
file.close()
4. Using with Statement
The with statement automatically closes the file:
with open("sample.txt", "r") as file:
content = file.read()
print(content)
with open("sample.txt", "a") as file:
file.write("\nAdding new line safely.")
5. Advanced I/O
- Binary files –
"rb"and"wb"modes for reading/writing binary files. - File positioning –
seek()andtell()methods.
with open("sample.txt", "r") as file:
print(file.tell()) # Current position
print(file.read(5)) # Read 5 characters
file.seek(0) # Move pointer to start
- Checking file existence using
osmodule:
import os
if os.path.exists("sample.txt"):
print("File exists")
else:
print("File does not exist")
6. Practice Exercises
- Create a text file and write 5 lines of your choice.
- Read the file and print each line one by one.
- Append 3 more lines to the same file.
- Use
seek()andtell()to read specific parts of the file. - Try opening a file in binary mode and read/write some data.