Working with files in Python
Use Python’s built-in open() to create and modify files. You choose a mode like "a" (append) or "w" (write) to control how data is saved.
Open or create a file
Append mode creates the file if it doesn’t exist, or adds to the end if it does:
# Open (or create) a file named "Customers.txt" in append mode
customer_file = open("Customers.txt", "a")
customer_file.write("John Doe, 2025-01-15, VIP\n")
customer_file.close()
Why close? .close() flushes data to disk. Alternatively, prefer a context manager:
# Best practice: context manager closes automatically
with open("Customers.txt", "a") as customer_file:
customer_file.write("Jane Doe, 2025-01-16, STANDARD\n")
Append ("a") vs Write ("w")
"a" adds to the end; "w" overwrites the whole file (or creates a new one):
# WARNING: "w" will overwrite the file
with open("log.txt", "w") as f:
f.write("Session started\n")
with open("log.txt", "a") as f:
f.write("User signed in\n")
Writing multiple values on one line
Store several pieces of data separated by commas (CSV-friendly):
name = input("Enter customer name: ")
appointment = input("Enter appointment date (YYYY-MM-DD): ")
vip = input("VIP (yes/no): ")
with open("CustomerRecords.txt", "a") as f:
f.write(name + ", " + appointment + ", " + vip + "\n")
print("Customer record saved!")
Task 1 – Create MyFriends.txt
Open (or create) MyFriends.txt in append mode and write 5 names on separate lines.
# Append five names to MyFriends.txt, one per line
with open("MyFriends.txt", "a") as friends_file:
for i in range(5):
name = input("Enter friend name " + str(i+1) + ": ")
friends_file.write(name + "\n")
print("Names have been saved to MyFriends.txt")
Task 2 – Create ALevels.txt
Write each student’s name and three A-Level subjects on one line, separated by commas. Do this for at least three students.
# Collect details for 3 students and append to ALevels.txt
with open("ALevels.txt", "a") as alevels_file:
for _ in range(3):
student = input("Enter student's name: ")
subject1 = input("Enter first A-Level subject: ")
subject2 = input("Enter second A-Level subject: ")
subject3 = input("Enter third A-Level subject: ")
alevels_file.write(student + ": " + subject1 + ", " + subject2 + ", " + subject3 + "\n")
print("ALevel records have been updated!")
Best practices
- Prefer
with open(...)so files always close properly—even on errors. - Use
"a"to add to existing files;"w"to start fresh and overwrite. - Add
"\n"to ensure each record is on its own line. - Choose a consistent delimiter (comma, tab) if you’ll read the data back later.