File Handling

Course Content

Saving data

You will have to save data at some point in your program. 

There are various ways to do this:

At Higher we will concentrate only on text/csv files. There are various methods to access files in Python but we will be using the methods in the File Object.

Reading Text/CSV Files

When a file is opened you have to specify how it should be opened. This is what type of access you will be using. When opening a file we can set the following modes:

Some other Python File Access Modes

File Reading Example Pseudocode

Assuming that the file exists in the same folder as the Python Program the pseudocode below shows opening a file for reading and reading all of the contents into a variable called filecontents.

OPEN FILE(SAMPLEFILE.txt) FOR READING

filecontents = FILE.READ

CLOSE FILE

File Reading - Python Example

The code below would open the file for reading. Again assuming that the file sampleFile.txt is in the same folder. When the file has been read into the variable called filecontents

Once the with loop ends the file is closed. Remember to put Close File in pseudocode.

Different ways to read from a file

There are different ways to read the contents of a file:

Processing a CSV File

What is a CSV File

A CSV file is simply a plain text file where each piece of data is separated by a comma. And each new record is on a new line e.g. below:

Mark,43

Joanna,54

It is important for you to analyse the file structure as this will dictate how the file is to be read and processed. The order of the pieces of data is important. Whether a file extension is CSV or plain text you should process the file in the same way.

Processing a CSV File

Reading CSV Files Tutorial Video

2 - Reading CSV Files.mp4

Writing Files

In the most basic method of writing to a file you write a string at a time, and when needed will put a new line character at the end so that the next string will be on a new line.

Basic File Writing - Pseudocode

OPEN FILE("newfile.txt" for WRITING)

WRITE Python is great fun" TO FILE

WRITE "This text will be on another line" TO FILE

CLOSE FILE

Basic File Writing Python

Creating a new CSV File

When you need to create a CSV file from either variables, arrays or records you will need to create a single line of a file at one time. You will notice in the example below that we add the \n character at the end. This is Python's End of Line character so that the next writeline operation will take place on a new line.

Creating Files

If you were creating a file using only some records from an array you could open the file BEFORE traversing the array.

This is far more efficient than opening and closing the file repeatedly.

Another example of creating a CSV file.

The code below would take in an array of forenames, surnames and Scottish Candidate Numbers and will write them to a CSV file

Creating a CSV File Tutorial Video

3 - Writing CSV Files.mp4