Lecture 11

Review

  1. If your source code file is at: Projects/FilesReview/src/main/open_data.py and the data file you want to access is at: Projects/FilesReview/data/2015-06-17/collected.dat write a relative path that opens the data file from the open_data.py file.
  2. What happens if you try to open a non-existent file for reading?
  3. What happens if you try to open a non-existent file for writing?

Files

File Formats

In the writing examples earlier, we were just writing sentences to a file with no regard for how to make extracting the information as easy as possible. The reading examples earlier were just spitting out to the user the contents of the file. Often, you will want the information stored in a file to be easily extracted by your program. To accomplish this, you must think about the best way to store data in the file.

Usually, each line in a file represents a single record (i.e. everything related to a single data point, single person, or single element of interest) since you can use the readline and readines methods or the for-loop iteration example to read in one line at a time and process it.

Within a line, it is a very good idea to put values in the same order on each line. That makes processing the data much easier. If you're storing names, birthdates, and favorite colors, don't sometimes store them as name, birthdate, color and other times as birthdate, color, name

Decide how the fields in a record are separated. Commas are traditional, but if you're saving text from the user that could contain spaces, then you might want a different separator. Tabs are also traditional and less likely to cause problems than commas. But, you can use any separator you want.

Which of the following would be easier for a program to read?

Alice	10/24/86	red
Bob	3/14/90	green
Carol	7/14/80	blue

or

Alice,10/24/86,Red
Bob	1990-03-14	green
Carol	blue	7/14/80

Once you've decided on a format for the file, you will likely be using readline, readlines, and writelines to read and write files.

Write a program that asks the user for their name, birthdate, and favorite color. Save this information to a file (have the user specify the file). Continue asking until the user wants to stop. Write another program that reads this information and prints it to the screen.

Midterm Review

Based on the midterm review survey, the order for the review topics are:

  1. Lists and Tuples
  2. Files
  3. Loops
  4. Python Basics
  5. Boolean Expressions
  6. if statements

Lists and Tuples

The specific questions were:

Files

The specific questions were:

Loops

The specific questions were:

Python basics

The specific questions were:

Boolean Expressions

The specific questions were:

if statements

The specific questions were:

Midterm Review Page

The midterm review page has additional practice/review that you may find helpful: midterm.html.

<< Previous Notes Daily Schedule Next Notes >>