This is Data Science. We care about data and a lot of our data will be stored in files, especially as we work on intro programming. Where else might data come from if not files? Databases. Web retrieval. Direct sensor connections. For today, we will learn the basics about reading from files.
Today also introduces an important step in expanding the complexity of programs that you can write. So far you have only been able to store one value at a time in a variable, and this has limited what we can do. The one exception was our Image Manipulation lab where we read in an entire image of pixels into a single "object" variable ... it hid the more complex data type from you.
A list is an object that stores a sequence of values, allowing you to easily store and alter lots of values at once. Today introduces the basics of lists.
Read Chapter 7 ... all of it.
We will discuss and learn about:
This program opens a text file that has integers one per line. It prints their sum:
sum = 0
fh = open('numbers.txt')
for line in fh:
sum = sum + int(line)
print("File numbers sum =", sum)
This program opens a text file of words and finds all names that follow "Dr. " to print them out.
fh = open('bigbook.txt')
for line in fh:
line = line.lower()
if "dr." in line:
start = line.find("dr.")+4
end = line.find(" ",start)
name = line[start,end]
print(name + '\n')
fh.close()
This program creates a list of soccer positions and parses through it
#create list of positions
positions = ["goalie", "center back", "right fullback", "left fullback",
"center mid", "left mid", "right mid", "striker",
"right wing", "left wing"]
# go through positions
for pos in positions:
if "back" in pos:
print(f"{pos} saves the game by being an amazing defender")
elif "mid" in pos:
print(f"{pos} does their best to control the field")
elif "striker" in pos:
print(f"{pos}'s main job is to score")
elif "wing" in pos:
print(f"{pos} has the hard job of crossing it beautifully to the pk area")
else:
print(f"{pos} is the most important position. Let's just agree on that")
print("And yes, there are 11 players in that list ... two center backs")