14: Reading data from a file in python

Try it:

Use and store data in files
Reading data from a file in python

Below you’ll see some example python code writes to a file called instructions.txt

Press Ctrl + Enter  to run the code.

This code will read a list of jobs from the file todo.csv and then display which jobs are marked as being done and which ones are marked as being not completed yet:

Left: CSV file, Right: program output

Challenges:

Start by running the code.

  1. Add another job to todo.csv

    The format for the CSV file is number, task, done (y/n) – add a new line to the file todo.csv describing a task (e.g. brush your teeth)

  2. Make a variable called remaining_jobs which stores the number of jobs which haven’t been done yet

    There are two main ways you can do this. You could set remaining_jobs to zero at the start of the program and increase it by one every time you add a task to the list jobs_to_do or you could use the len() function to count how many items are in the jobs_to_do list

  3. Make a variable called total_jobs which stores the total number of jobs (done or not done yet)

    You could count how many lines are in the CSV file or you could add up the number of items in both jobs_to_do and jobs_done

On the next page you’ll get some code with both syntax and logic errors

KPRIDE

KPRIDE stands for Keywords, Predict, Run, Investigate, Debug and Extend and it’s a way of helping you explore and understand python code. Click on the image below for a set of KPRIDE activities for this python skill.

Leave a Reply

Your email address will not be published. Required fields are marked *