Python File Handling
PythonPython makes it easy to read and write files. This is essential for real-world projects.
Key Points
- Use
open()to open files - Modes:
r(read),w(write),a(append),r+(read+write) - Always use
withstatement — it auto-closes the file wmode overwrites the file,amode adds to it- Use
.read(),.readline(), or.readlines()
Example — PYTHON
# Writing to a file
with open("students.txt", "w") as f:
f.write("Rahul - 85\n")
f.write("Priya - 92\n")
f.write("Amit - 78\n")
print("File written! ✅")
# Reading entire file
with open("students.txt", "r") as f:
content = f.read()
print(content)
# Reading line by line
with open("students.txt", "r") as f:
for line in f:
print(line.strip())
# Appending to file
with open("students.txt", "a") as f:
f.write("Sara - 88\n")
print("Data appended! ✅")
# Count lines in file
with open("students.txt", "r") as f:
lines = f.readlines()
print(f"Total students: {len(lines)}")
# Writing CSV-style data
students = [
{"name": "Rahul", "marks": 85},
{"name": "Priya", "marks": 92},
]
with open("marks.csv", "w") as f:
f.write("Name,Marks\n")
for s in students:
f.write(f"{s[\"name\"]},{s[\"marks\"]}\n")
print("CSV created! ✅") Result
File written! ✅
Rahul - 85
Priya - 92
Amit - 78
Rahul - 85
Priya - 92
Amit - 78
Data appended! ✅
Total students: 4
CSV created! ✅
Rahul - 85
Priya - 92
Amit - 78
Rahul - 85
Priya - 92
Amit - 78
Data appended! ✅
Total students: 4
CSV created! ✅