# Writing to a file
file = open("scores.txt", "w")
file.write("Alice,92\n")
file.write("Bob,78\n")
file.close()
# Reading from a file
file = open("scores.txt", "r")
content = file.read()
file.close()
Modes: "r" (read), "w" (write — overwrites), "a" (append — adds to end)
Always close files after use — or use with open(...) as f: which auto-closes
Databases
Structured Data Storage
A database stores data in structured tables (relations). Each table has columns (fields) and rows (records). A DBMS (Database Management System — e.g. MySQL) manages access to the data.
Primary key: a unique field that identifies each record. e.g. StudentID. No two records have the same primary key.
Foreign key: a field in one table that links to the primary key of another table — creates relationships
Flat File vs Relational Database
When to Use Each
Flat file: all data in one table; simple; no linking. Leads to data duplication. OK for simple data (e.g. a contacts list).
Relational database: multiple linked tables; avoids duplication; more complex; uses SQL to query. Used for complex systems (e.g. school management system).
SQL example:SELECT name, grade FROM students WHERE grade = 'A';
Exam Practice
Have a go at this question
Edexcel-style question
A school stores student data. Explain why a relational database is more suitable than a flat file for this purpose.
3 marks
A relational database stores data in linked tables [1], which avoids repeating the same data (no duplication) — for example, teacher details can be stored once and linked to many classes [1]. It also allows complex queries across multiple tables using SQL [1].
Key Takeaways
What to Remember
File modes: "r" read, "w" write (overwrites), "a" append
Primary key: unique identifier for each record (no duplicates)