Extra Credit Lab Lecture

More Python

Topics

  • persistence
  • files
    • opening
    • reading from
    • writing to
    • processing data from
  • lists
    • iterating over
    • indexing
  • list operations
  • standard list methods
  • dictionaries
  • the pickle package

A note on persistence

All the stuff we've done before now has dealt exclusively with data in memory. But, what if we wanted to store things? How would we do that?

Files

  • good for storing data that needs to stay on the computer as its powered off
  • slower than memory!

Opening files in Python is just as simple as knowing the name of the file.

In [14]:
myfile = open("info.txt")
count = 0

for line in myfile:
    count = count + 1
print('Line Count:', count)
Line Count: 2
In [15]:
mynewfile = open("info.txt")

for line in mynewfile:
    print(line)

What if I wanted to get just my name and age, as variables, so I can do fun things with them?

In [ ]:
infofile = open("info.txt")

firstline = infofile.readline()
secondline = infofile.readline()

f = firstline.split()
s = secondline.split()

print(f)
print(s)

So, we just took a hard right turn into Listville.

Lists! (accidentally)

  • you've seen lists before, remember?
In [ ]:
my_friends = ["Bob", "Susan", "Noah", "Amanda"]

for friend in my_friends:
    print("Hello,", friend)

List are sequences of items that we iterate through. There are a number of built-in Python functions that operate

Back to files

So, what if we want to write something to a file?

In [ ]:
testfile = open("test.txt", "w")
line1 = "Here's some test data."
testfile.write(line1)

Dictionaries

  • key-value pairs
  • not indexable
  • access keys through square brackets
In [ ]:
counts = {'chuck' : 1 , 'annie' : 42, 'jan': 100}

print(counts[chuck])
In [ ]:
counts = {'chuck' : 1 , 'annie' : 42, 'jan': 100}
for key in counts:
    print(key, counts[key])