š° What Is File Handling?
š¢ Lesson 3

File handling lets your Python programs interact with files on your computer ā read data from them or save data to them.
š You can:
- š Read data from files (like
.txt
,.csv
) - āļø Write or append new data
- šļø Use it to store logs, user input, or application data
š Basic Syntax: open()
pythonCopierModifierfile = open("filename.txt", "mode")
Mode | Purpose |
---|---|
'r' | Read (default) |
'w' | Write (overwrite file) |
'a' | Append (add to file) |
'x' | Create a new file (error if exists) |
'b' | Binary mode |
't' | Text mode (default) |
š Reading a File
ā
Method 1: Using open()
and read()
pythonCopierModifierfile = open("example.txt", "r")
content = file.read()
print(content)
file.close()
š Important: Always close()
the file when done.
ā
Method 2: Using with
(recommended)
pythonCopierModifierwith open("example.txt", "r") as file:
content = file.read()
print(content)
ā with
automatically closes the file when finished.
āļø Writing to a File
pythonCopierModifierwith open("output.txt", "w") as file:
file.write("Hello from Python!\n")
file.write("This will overwrite the file.")
š 'w'
mode creates a new file or overwrites an existing one.
ā Appending to a File
pythonCopierModifierwith open("output.txt", "a") as file:
file.write("\nThis line was added later.")
š 'a'
mode keeps existing content and adds new lines.
š Reading Line by Line
pythonCopierModifierwith open("example.txt", "r") as file:
for line in file:
print("š¹", line.strip())
ā strip()
removes newlines and extra spaces.
š§ Exercise 1: Write and Read
- Ask the user to enter 3 lines.
- Save them to
notes.txt
. - Then read and display the file content.
pythonCopierModifierwith open("notes.txt", "w") as file:
for i in range(3):
line = input(f"Enter line {i+1}: ")
file.write(line + "\n")
print("\nš File Contents:")
with open("notes.txt", "r") as file:
print(file.read())
š§ Exercise 2: Count Lines in a File
Assume a file students.txt
exists. Count how many lines it contains.
pythonCopierModifierwith open("students.txt", "r") as file:
lines = file.readlines()
print("š Total lines:", len(lines))
š Tip: Handle Missing Files Gracefully
pythonCopierModifiertry:
with open("missing.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("ā File not found.")
š Summary
- Use
open("file", "mode")
to access files. - Always use
with open(...)
to handle files safely. - Modes like
'r'
,'w'
,'a'
define how the file is opened. - Use
.read()
,.write()
, and.readlines()
to manipulate content.
Username : 0559403251
Password : 1134091580