File I/O
Computer Science · Python
Question 1 of 10
0The file notes.txt contains exactly this text: "apple 2\nmango 7\ndate 7\n" What does this Python code print? with open("notes.txt") as f: lines = f.readlines() print(len(lines))
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
File I/O explained
File I/O is how a Python program reads data from files and writes data to them. The built-in open function returns a file object, and the with statement closes the file automatically when its block ends, even if an error occurs inside it.
The mode string says what you want to do. "r" reads an existing file, "w" writes and replaces any existing content, "a" appends to the end, and "x" creates a new file and fails if the file already exists. Opening a file with "w" erases its old contents immediately, which is a common way to lose data by accident. A for loop over the file object reads one line at a time, which works for large files. Each line keeps its newline character, so strip() is often needed.
with open("scores.txt", "w") as f:
f.write("Ana,7\n")
f.write("Ben,9\n")
with open("scores.txt") as f:
total = 0
for line in f:
name, score = line.strip().split(",")
total += int(score)
print(total)
Worked example
The file scores.txt contains the two lines written above.
- The first line is "Ana,7" plus a newline. strip() removes the newline, and split(",") gives ["Ana", "7"].
- int("7") is 7, so total becomes 7.
- The second line gives 9, so total becomes 16.
- The with block ends and the file is closed. print(total) displays 16.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
The file notes.txt contains exactly this text: "lime 1\nlime 5\nfig 3\nlime 4\napple 1\n"
What does this Python code print? with open("notes.txt") as f: lines = f.readlines() print(len(lines))
Medium
The file notes.txt contains exactly this text: "\npear 7\nfig 5\npear 7"
What does this Python code print? count = 0 with open("notes.txt") as f: for line in f: if line.strip() != "": count += 1 print(count)
Hard
The file scores.txt contains exactly this text: "item score\nlime 3\nkiwi 6\ndate 8"
What does this Python code print? total = 0 with open("scores.txt") as f: next(f) for line in f: name, score = line.split() if int(score) >= 12: total += int(score) print(total)