Introducing
Your new presentation assistant.
Refine, enhance, and tailor your content, source relevant images, and edit visuals quicker than ever before.
Trending searches
E- LEARNING
Revise, Recap, Review
Find the errors in this person's attempt at reading from a file
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
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")
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)
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
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?
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!
How would I go about converting the age of my pets from years to months?
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
Task
Support sheet available if needed