Learn > Higher Computing Science > Higher Python Course > 12. File handling – Reading

File handling - Reading

File handling lets a program write (save) and read (load) data.
There are two types of file that you need to be familiar with:

  • Text files (.txt) store plain text, one value or line at a time
  • CSV files (.csv) use commas to separate values (e.g. name,age,score)
Jane
4B2
05/06/2012
Jane,4B2,05/06/2012
John,4A1,01/01/2012

Reading data from file

When reading data from a file, the same basic commands are used but with the “r” mode for reading.

  • open(“filename”, “r”) – Opens a file so the program can read from it.
  • readline() – Reads one line from the file each time it’s called.
  • strip() – Removes any extra spaces or the hidden newline (\n) at the end of each line.
  • split(“,”) – Splits the line at the commas
  • close() – Closes the file once all data has been read.

Array

def read_data():
    pupils = [str] * 5
    file = open("pupils.txt", "r")
    for i in range(5):
        pupils[i] = file.readline().strip()
    file.close()
    return pupils
John
Jane
Joe
Jack
Jessie

Parallel arrays

def read_data():
    pupils = [str] * 5
    ages = [int] * 5
    file = open("pupils.txt", "r")
    for i in range(5):
        pupils[i], ages[i] = file.readline().strip().split(",")
        ages[i] = int(ages[i])
    file.close()
    return pupils, ages
John,10
Jane,11
Joe,9
Jack,13
Jessie,14