Python Full Tutorial — Part 8

Programs that forget everything after running are not very useful.

File handling allows Python programs to store data permanently.

1. What is File Handling?

File handling means creating, reading, updating, and deleting files using Python.

2. Opening a File

Basic Syntax

file = open("data.txt", "r")
  

Common file modes:

3. Reading a File

Read Entire File

file = open("data.txt", "r")
content = file.read()
print(content)
file.close()
  

4. Reading Line by Line

Read Lines

file = open("data.txt", "r")
for line in file:
    print(line.strip())
file.close()
  

5. Writing to a File

Write Mode

file = open("data.txt", "w")
file.write("Hello Python\n")
file.write("File handling example")
file.close()
  

⚠️ Write mode deletes existing content.

6. Appending to a File

Append Mode

file = open("data.txt", "a")
file.write("\nNew line added")
file.close()
  

7. Using with (Best Practice)

Safe File Handling

with open("data.txt", "r") as file:
    print(file.read())
  

This automatically closes the file.

8. Real-World Example: User Log

Login Log File

def log_user(username):
    with open("users.log", "a") as file:
        file.write(username + " logged in\n")

log_user("admin")
log_user("guest")
  

9. Checking if File Exists

File Exists

import os

if os.path.exists("data.txt"):
    print("File exists")
else:
    print("File not found")
  

10. Why File Handling Matters

Key Takeaway

File handling connects programs with the real world. This is where Python stops being a toy and starts becoming a tool.

Next part: Error Handling (try, except).

Disclaimer:
This tutorial is for educational purposes only. Always handle files carefully to avoid data loss.