Load the data
After this: Read the file, cut each line into a name and two marks, keep them in a dictionary, and skip a bad line.
On this page · 6 sections · 3 checks
The file is three lines of text. The program needs three names, each with two numbers it can add up. Stage 1 turns the one into the other, and keeps going when a line is wrong.
One line at a time
Take the first line, Ana,72,85. It is one string with three things in it, separated by commas. split from "Strings" cuts it at the commas and gives back the three pieces: "Ana", "72" and "85". The marks are still text, so intInteger.parseInt turns them into numbers.
- The line arrives as text. In Python it still ends with the line-end character, so strip takes that off first.readAllLines has already taken the line end off.
split(",")cuts it at every comma. The pieces are kept, in order, in a box calledparts.parts[0]is the name.parts[1]andparts[2]are the marks as text; converting them gives 72 and 85, which go into a list calledmarks.
line = "Ana,72,85\n"parts = line.strip().split(",")name = parts[0]marks = [int(parts[1]), int(parts[2])]print(name)print(marks)run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
Keeping the three together
A dictionary from "Dictionaries and sets" fits: the name is the key and the list of marks is the value. After the three lines, the book holds Ana with [72, 85], Ben with [90, 60] and Cy with [88, 92], and book["Cy"] finds [88, 92].
A line that cannot be read
Files are typed by people. One day a line says Dee,abc,70. Converting abc fails with ValueErrorNumberFormatException, and a program with no plan for that stops there, with Ana stored and Cy never read. "Errors and debugging" gave the plan: put the converting lines in a try block, catch that one kind of error, say what happened, and carry on. The next line of the file is read as if nothing had happened.
- Run the programRun the program and step through it. The line is cut into three pieces, the converting line fails on abc, and the program jumps into the lines that handle the error instead of stopping.
line = "Dee,abc,70"try: parts = line.split(",") marks = [int(parts[1]), int(parts[2])] print(marks)except ValueError: print("Skipping bad line: " + line)print("Carrying on")run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The message names the line, so that the owner of the file can fix it. The program does not guess a mark for Dee: a guessed number would be a wrong number in the report, and nobody would know.
Stage 1
The lines go inside a function called load, which takes the file name and gives back the book. The last three lines call it and print two things you can check against the file: how many students there are, and Cy's marks.
def load(filename): book = {} with open(filename) as f: lines = f.readlines() for line in lines: try: parts = line.strip().split(",") book[parts[0]] = [int(parts[1]), int(parts[2])] except ValueError: print("Skipping bad line: " + line.strip()) return book
book = load("marks.txt")print(len(book))print(book["Cy"])3 [88, 92]
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.HashMap;import java.util.List;
public class Main { static HashMap<String, List<Integer>> load(String filename) throws IOException { HashMap<String, List<Integer>> book = new HashMap<>(); List<String> lines = Files.readAllLines(Path.of(filename)); for (String line : lines) { try { String[] parts = line.split(","); book.put(parts[0], List.of(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]))); } catch (NumberFormatException e) { System.out.println("Skipping bad line: " + line); } } return book; }
public static void main(String[] args) throws IOException { HashMap<String, List<Integer>> book = load("marks.txt"); System.out.println(book.size()); System.out.println(book.get("Cy")); }}3 [88, 92]
bookstarts empty, and the file's lines are read intolines, as in "Input, files and the standard library".- The loop takes one line at a time. Inside the
try, the line is cut intoparts, and the name becomes a key whose value is the list of the two converted marks. - If a mark cannot be converted, the exceptcatch lines run instead: the line is reported, and the loop goes on to the next one.
- When the loop is done,
loadgives the book back.
Change "Cy" on the last line to "Ana" and run it again. The same program over a file whose second line is Dee,abc,70:
Check yourself
The file marks.txt holds three lines: Ana,72,85, Dee,abc,70 and Cy,88,92. What does stage 1 print?
def load(filename): book = {} with open(filename) as f: lines = f.readlines() for line in lines: try: parts = line.strip().split(",") book[parts[0]] = [int(parts[1]), int(parts[2])] except ValueError: print("Skipping bad line: " + line.strip()) return book
book = load("marks.txt")print(len(book))print(book["Cy"])import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.HashMap;import java.util.List;
public class Main { static HashMap<String, List<Integer>> load(String filename) throws IOException { HashMap<String, List<Integer>> book = new HashMap<>(); List<String> lines = Files.readAllLines(Path.of(filename)); for (String line : lines) { try { String[] parts = line.split(","); book.put(parts[0], List.of(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]))); } catch (NumberFormatException e) { System.out.println("Skipping bad line: " + line); } } return book; }
public static void main(String[] args) throws IOException { HashMap<String, List<Integer>> book = load("marks.txt"); System.out.println(book.size()); System.out.println(book.get("Cy")); }}Complete the missing line so that the line of text is cut at its commas into three pieces, kept in the box parts. Over the three-line file, the program then prints 3 and [88, 92].
def load(filename): book = {} with open(filename) as f: lines = f.readlines() for line in lines: try: ____________________ # ← cut the line into its three pieces, in the box parts book[parts[0]] = [int(parts[1]), int(parts[2])] except ValueError: print("Skipping bad line: " + line.strip()) return book
book = load("marks.txt")print(len(book))print(book["Cy"])import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.HashMap;import java.util.List;
public class Main { static HashMap<String, List<Integer>> load(String filename) throws IOException { HashMap<String, List<Integer>> book = new HashMap<>(); List<String> lines = Files.readAllLines(Path.of(filename)); for (String line : lines) { try { ____________________ // ← cut the line into its three pieces, in the box parts book.put(parts[0], List.of(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]))); } catch (NumberFormatException e) { System.out.println("Skipping bad line: " + line); } } return book; }
public static void main(String[] args) throws IOException { HashMap<String, List<Integer>> book = load("marks.txt"); System.out.println(book.size()); System.out.println(book.get("Cy")); }}Complete the missing line so that a mark which is not a number is caught, reported, and skipped. Over the file with the Dee,abc,70 line, the program then prints the skip message, 2, and [88, 92].
def load(filename): book = {} with open(filename) as f: lines = f.readlines() for line in lines: try: parts = line.strip().split(",") book[parts[0]] = [int(parts[1]), int(parts[2])] ____________________ # ← catch the error a bad mark raises print("Skipping bad line: " + line.strip()) return book
book = load("marks.txt")print(len(book))print(book["Cy"])import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.HashMap;import java.util.List;
public class Main { static HashMap<String, List<Integer>> load(String filename) throws IOException { HashMap<String, List<Integer>> book = new HashMap<>(); List<String> lines = Files.readAllLines(Path.of(filename)); for (String line : lines) { try { String[] parts = line.split(","); book.put(parts[0], List.of(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]))); ____________________ // ← catch the error a bad mark raises System.out.println("Skipping bad line: " + line); } } return book; }
public static void main(String[] args) throws IOException { HashMap<String, List<Integer>> book = load("marks.txt"); System.out.println(book.size()); System.out.println(book.get("Cy")); }}Honesty notes
- Cut a line at its commas with split, read the three pieces by position, and convert the two marks from text to numbers.
- Keep the name as the key and the list of marks as the value, so that one name finds its marks.
- Put the converting lines in a try block and catch the one error a bad mark raises (ValueError in Python, NumberFormatException in Java), so that the line is reported and the next one is read.
- Give the loading lines a function of their own, load, that takes the file name and gives back the book.