Reading and writing to a flat-file database

Some data in a program is created and used only while the program is running. This data will disappear when the program is closed. However, sometimes programs need to store data. A simple way to store data values in a persistent store is to use a flat-file database.

It is a key skill to write and read data to files when programming.

curriculum-key-fact

It is useful to know how to edit a CSV or text file using one or more languages. We will be using Python and Java in the following examples, but you may prefer to use different languages.

Example: Inputting a name and number into a CSV

In the following example, we look at how a program could input a name and number into a CSV. The code asks a user to input a single name and telephone number and then adds this information as "name, number" - eg "John, 0501111222".

Open the contacts.csv file in append mode (“a”)
Make the contacts file available for editing
Request the user to input a single name
Store this name as a variable called name
Request the user to input a phone number
Stores the number as a variable called phno
Concatenate (zxrncdm) the variables name and phno together with “,” to separate them and a newline character “\n” at the end.
Write this string to the csv file.