Welcome back. Let's learn files

by Elliott Hauser

22 Mar 2016

Spring Break Hacks

Submit em via pull request.

Guests on Thursday!

Two SILS alumnae are joining us. One is a developer and the other works with developers. It’ll be a great class! There are three readings I’ve assigned, about diversity in tech.

We’ll spend the first bit of class setting up git on Cloud 9. Then we’ll have a group discussion with our guests. Please come prepared to learn and ask questions of them!

Cloud 9

You should be set up on Cloud 9’s free plan. We’ll use that starting Thursday.

Python 3

We’ll be using Python 3 in Cloud9 and Trinket from here out. Remember your print() functions.

sep=" " lets you specify what the seperator between arguments is. It defaults to a space.

end='\n' lets you specify what to do at the end of the print functin. It defaults to a newline.

You can make anonymous Python 3 trinkets on Trinket for free. If you want the convenience of saving your Python 3 trinkets to your account, you can use code inls560 to get our premium plan at a huge discount of two bucks a month.

When we start running Python on Cloud 9, remember to type python3 instead of python.

Files

There are a few core actions you should be able to perform on files:

  • Open them (Dr. Chuck)
  • Search/extract information from them (Dr. Chuck)
  • Build a data structure from them (not really Dr. Chuck)
  • Explore your data (not really Dr. Chuck)
  • Print a table from your data (not Dr. Chuck)

We’ll do all of these today.

Something Dr. Chuck didn’t cover: the with statement. This is the Pythonic way to open a file:

with open("sales.csv") as file:
  sales_raw = file.read()
  # Or, if you need lines:
  sales_lines = file.readlines()

Otherwise you’ll have to open and close the file handler and it’s a pain.

Lists of Lists

Making a list full of lists gives you some interesting powers. First, you can think of each item in the main list as a row and each item in the interior lists as a cell/column. As long as you keep the lengths constant you’ve got what amounts to a spreadsheet, but in Python!

Here’s how you can visualize a list of lists:

[ [... , ... , ...]
  [... , ... , ...]
  [... , ... , ...]
  [... , ... , ...]
  [... , ... , ...] ]

This one has five rows and three columns.

To work with lists of lists you’ll nee lots of slicing and indexing. Remember the list[x:y:z] syntax.

Let’s get to work! I recommend you read over questions 1-3 briefly and then go straight to exercise 4. Let me orient you briefly.

Elliott Hauser is a PhD Student in information science at UNC Chapel Hill. He's hacking education as one of the cofounders of Trinket.io. Find Elliott Hauser on Twitter, Github, and on the web.