Programs that forget everything after running are not very useful.
File handling allows Python programs to store data permanently.
File handling means creating, reading, updating, and deleting files using Python.
file = open("data.txt", "r")
Common file modes:
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()
file = open("data.txt", "r")
for line in file:
print(line.strip())
file.close()
file = open("data.txt", "w")
file.write("Hello Python\n")
file.write("File handling example")
file.close()
⚠️ Write mode deletes existing content.
file = open("data.txt", "a")
file.write("\nNew line added")
file.close()
with (Best Practice)
with open("data.txt", "r") as file:
print(file.read())
This automatically closes the file.
def log_user(username):
with open("users.log", "a") as file:
file.write(username + " logged in\n")
log_user("admin")
log_user("guest")
import os
if os.path.exists("data.txt"):
print("File exists")
else:
print("File not found")
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).