Browser lab15 min+60 XP

Reading files

Load data back in, line by line, and turn it into lists and numbers.

0% done

Code runs right here in your browser. Nothing to install.

TASK 1

Learn it

Key idea

Loop over a file line by line, then strip and split each line.

Key words
"Ava,90\n"one line from the file"Ava,90"["Ava", "90"]("Ava", 90).strip().split(",")int() on the score
One line from the file becomes useful data.

Open a file for reading with open("file.txt") (reading is the default mode, "r"). f.read() gives the whole file as one string. f.readlines() gives a list of lines.

The neatest way is to loop over the file: for line in f: gives one line at a time. Each line ends with \n, so use line.strip() to remove it.

Remember that everything read from a file is a string. Use split and int() to turn "Ava,90" into a name and a number.

Real life linkIn this browser lab, files are stored in memory and disappear when the program ends. On your own computer, the same code creates real files in your project folder.
Example code
with open("guests.txt", "w") as f:
    f.write("Ava\nBen\nCleo\n")

with open("guests.txt") as f:
    for line in f:
        print("Welcome,", line.strip())

with open("guests.txt") as f:
    names = f.readlines()
print(len(names), "guests")
TASK 2

Try it yourself

+10 XP

The code first creates marks.txt. Read it back line by line, convert each line to an int, and print the total and the highest mark: Total: 247 and Highest: 91.

Create a free account to start this lab

Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.

TASK 3

Capture the flag

+10 XP

Which string method removes the newline from the end of a line read from a file?

Create a free account to start this lab

Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.

HOMEWORK

Leaderboard from a file

+20 XP

The code creates scores.txt with lines like Ava,90. Read it, build a list of (name, score) tuples with the score as an int, sort it from highest to lowest, and print a numbered leaderboard: 1. Max 150.

Create a free account to start this lab

Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.