Introducing 

Prezi AI.

Your new presentation assistant.

Refine, enhance, and tailor your content, source relevant images, and edit visuals quicker than ever before.

Loading…
Transcript

Lesson 8 - Writing to a file

E- LEARNING

Revise, Recap, Review

Objectives

Find the errors in this person's attempt at reading from a file

Lesson Objectives

To learn the difference between 'r', 'w' and 'a' when using files in python

Use a loop to write values to a file

Process data stored in an external file

Modes

Theory

When handling files, the mode you open your file in is important:

file = open("file.txt", "r")

file = open("file.txt", "w")

file = open("file.txt", "a")

Opening to write

Almost the same as reading from a file, just change the mode!

Append mode means if the file isn't there, make it.

If it does already exist then just ADD data to it (in write mode everything gets overwritten every time)

Give it a go

Multiple inputs

Sometimes, we may want to write multiple records to our file.

Like most things we want to do more than once, we can achieve this by using a loop

Calculations

Sometimes, we need to perform some calculations on the data that we hold in external files

If I wanted to calculate the average age of the pets in the file, how would I do this?

A possible solution

1. Declare a variable (0) to keep a running total of the ages

2. Declare a variable to act as a counter

3. step thorough each line and split the data

4. Add the age of each pet to the running total variable

5. Increment the counter by 1

It's worth remembering we are now READING data, so we will need to change the mode!

What does that look like in python?

More calculations

How would I go about converting the age of my pets from years to months?

One way

We could use a loop and a lists

1. step through each line, splitting the data

2. Assign fields variable names

3. create a new variable to store the age in months and multiply age by 12

4. print the pet name and new age

5. next iteration

And in python?

Task

Task

Support sheet available if needed

Learn more about creating dynamic, engaging presentations with Prezi