MathubLearn / Practice / Excel
CSCI 127 Joy and Beauty of Data · Unit 2: Data structures · on Exam 2

2.2 Files

Study notes for Files in CSCI 127 Joy and Beauty of Data at Montana State University: the big ideas, code you should know, a worked example, common mistakes and an exam tip. The same topic has endless practice questions and flashcards in Mathub.

Big ideas

Code you should know

Write, then read it back
with open("scores.txt", "w") as f:
    f.write("Ana,91\n")
    f.write("Ben,78\n")
    f.write("Cy,85\n")

total = 0
count = 0
with open("scores.txt") as f:
    for line in f:
        name, score = line.strip().split(",")
        total += int(score)
        count += 1
        print(name, "->", score)
print("average", total / count)
Output
Ana -> 91
Ben -> 78
Cy -> 85
average 84.66666666666667
Counting lines and words
with open("poem.txt", "w") as f:
    f.write("Roses are red\nviolets are blue\n")

with open("poem.txt") as f:
    lines = f.readlines()
print(len(lines), "lines")
words = 0
for line in lines:
    words += len(line.split())
print(words, "words")

with open("poem.txt", "a") as f:
    f.write("sugar is sweet\n")
print(open("poem.txt").read())
Output
2 lines
6 words
Roses are red
violets are blue
sugar is sweet

Worked example

A file has the lines 3, 10, 4. What does this print?
total = 0
with open("nums.txt") as f:
    for line in f:
        total += int(line)
print(total)
Show the solution
17. int() ignores the newline at the end of each line, so the three numbers add up.

Common mistakes

Exam tipKnow the three modes cold and the shape of the read-loop: open, loop over lines, strip, split, convert, accumulate.

Keep going in Mathub

Mathub is free for Montana State students: an endless quizzer with worked explanations, one-question lessons, flashcards, exam prep checklists, the class calendar with every deadline, a grade calculator and a study board for CSCI 127.