Reading files
Load data back in, line by line, and turn it into lists and numbers.
Code runs right here in your browser. Nothing to install.
Learn it
Loop over a file line by line, then strip and split each line.
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.
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")
Try it yourself
+10 XPThe 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.
Capture the flag
+10 XPWhich 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.
Leaderboard from a file
+20 XPThe 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.