๐ฐ 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