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
with open("data.txt") as f:opens a file and closes it automatically at the end of the block. Modes:"r"read (default),"w"write (erases!),"a"append.- Reading:
for line in f:visits each line (with its trailing\n, sostrip()it);f.read()gives the whole text;f.readlines()a list of lines. - Writing:
f.write(text)writes exactly what you give it, so add\nyourself. Numbers must be converted withstr()or an f-string. - CSV-style data: split each line on the delimiter,
line.strip().split(","), convert the fields you need, and accumulate totals, counts or a list of records. - A missing file raises
FileNotFoundError; check the name and that the file sits next to your program (or give a full path).
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
- Opening with
"w"when you meant to add: the old contents are gone. - Forgetting
strip(), so the last field keeps a newline and"85\n" == "85"is False. - Writing a number with
f.write(42)(TypeError); write a string. - Reading the file twice without reopening it: the second loop sees nothing.
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.