Slides badge

File Handling

Learning Intentions

  • Understand the term 'predefined function'

  • Identify and use appropriate predefined functions

Success Criteria

  • Be able to explain the term predefined function
  • Be able to identify and describe the predefined functions specified at Higher level

Reading and writing files

  • At Higher, you are expected to be able to read and write to text files. 

  • It's relatively straight forward and easy to in Python.

Reading a text file, line by line

  • The Python code for this is shown below (note we are using a subroutine to read the file):
def readFile(filename, lines):

    with open(filename, 'r') as f:

        for line in f.readlines():
          #Add each line to the lines list
          lines.append(line)

lines = []

readFile("countries.txt", lines)
print(lines)

CSV files

  • A CSV or Comma Separated Values file is much like a spreadsheet, consisting of columns and rows.
  • In reality, a CSV is just a text file.
  • Below is a very simple example of this
Francis,Burnham,36
Peter,Roosevelt,94
Adam,Smith,41

CSV files

  • To work with a CSV file we need to look at each line of the file individually, and then use the 'split' function to split the row into columns
def readFile(filename, list1,list2):
    with open(filename, 'r') as csv_file:
        for row in csv_file.readlines():

          #Remove the \n line terminator character
          row = row[0:-1]
          #Split the row string by commas
          row = row.split(",")
          #Each index is a column
          print(row[0])
          print(row[1])
          print(row[2])

The split function

  • The split function is used on each row of the CSV to convert the line (which is a string) into an array.
def readFile(filename, list1,list2):
    with open(filename, 'r') as csv_file:
        for row in csv_file.readlines():

          #Remove the \n line terminator character
          row = row[0:-1]
          #Split the row string by commas
          row = row.split(",")
          #Each index is a column
          print(row[0])
          print(row[1])
          print(row[2])

The split function

  • The split function is used on each row of the CSV to convert the line (which is a string) into an array.
nums = "1,2,3,4"
##Split the row string by commas
numbers = nums.split(",") 

The numbers variable will contain an array with the following:

[1, 2, 3, 4]

CSV files

  • When working with CSV files at Higher level, it is appropriate to use a record structure or several parallel arrays to store details from the CSV file.
  • Again, this is relatively straight foward to do.
Francis,Burnham,36
Peter,Roosevelt,94
Adam,Smith,41

Working with parallel arrays and CSV files

  • The Python code for working with CSV files is shown below (note we are again using a subroutine to read the file):
text_file = open("write.txt", "w")

text_file.write("Hello, this is a test to see if this will write")

text_file.close()

CSV files and record structures

class pupil:
  forename = ""
  surname = ""
  grade = 0

def readFile(filename, output):
  with open(filename, 'r') as csv_file:
        for row in csv_file.readlines():
          row = row[0:-1]
          processedRow = row.split(",") #Split the row string
          output[position] = pupil() #IMPORTANT
          output[position].forename = processedRow[0]
          output[position].surname = processedRow[1]
          output[position].grade = processedRow[2]
   csv_file.close()

pupils = [pupil()] * 200
readFile("pupils.csv", pupils)

Using the provided CSV files

 

  • census2010.csv [state name, average temperature, population]
  • titanic.csv [class, survived, full name, cabin number]
  • flavours.csv [flavour name, flavour type]

 

write a program to store each row from the file in either a record structure or parallel arrays (use the names in the square brackets above to help). 

Task

Writing to a text file with Python

  • We can use similar code to write to a text file in Python.
def writeFile(filename, text):
  with open(filename, 'w') as text_file:
    text_file.write(text)
    text_file.close()

writeFile("test.txt", "Hello there world!")

Writing data to a CSV file

import csv

def writeFile(filename, forenames, surnames):
  with open(filename, 'w') as text_file:
    csv_file = csv.writer(text_file)

    for i in range(0, len(forenames)):
      #This bit is turning the values into an array
      row = [forenames[i], surnames[i]]
      csv_file.writerow(row)

    text_file.close()

forenames = ["John", "James", "Gillian"]
surnames = ["Smith", "Blogs", "McGlashan"]

writeFile("test.csv", forenames, surnames)

Using the data provided in the CSV file flavours.csv, read all the data into parallel arrays. At the end of the parallel arrays, using the Python list.append function, add 'kiwi' as 'fruity'.

Task

Presentation Overview
Close
JB
File Handling
© 2020 - 2024 J Balfour
17:17 | 29-04-2024
Join Live Session
Start Remote
Save Progress
Slideshow Outline
Presenter Mode
Widget Screen
Canvas Controls
Random Selector
Timer
Volume Meter
Binary Converter
Python Editor
Show Knox 90
Provide Feedback
Help
!
Keywords
    DragonDocs Management
    Random selector
    Sections
      Binary conversion
      Denary to binary conversion
      Binary to denary conversion
      Feedback 👍
      Accessibility

      Apply a filter:

      ×
      All slideshow files