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.

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".

Here is the algorithm presented in pseudocode:

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.

This is how the code would look in Python:

file = open("contacts.csv", "a") name = raw_input("Please enter name.") phno = raw_input("Please enter phone number.") file.write(name + "," + phno + "\n")

This is how the code would look in Java:

import; import; import; import; import java.util.Scanner; public class phonebook { public static void main(String[] args) { String name, phno; Scanner scanner = new Scanner (; System.out.print("Please enter name"); name =; // Get what the user types. System.out.print("Please enter phone number"); phno =; try { File file = new File("./contacts.csv"); if (!file.exists()) { // if file doesnt exist, then create it file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); BufferedWriter bw = new BufferedWriter(fw); bw.write(name + "," + phno + "\n"); bw.close(); } catch (IOException e) { e.printStackTrace(); } } }