New: Complete Beginner's Guide to Coding is now available in Premium
Updated: Indian Govt Exam roadmaps now include salary breakdowns & timelines
Tip: Use the Career Hub to explore all career paths in one place
Tutorials Python Python File Handling

Python File Handling

Python

Python 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 with statement — it auto-closes the file
  • w mode overwrites the file, a mode 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! ✅