Helpful examples

These should come in handy when completing the assignment.

Test reading a csv-file

  • make a folder in the notebooks-directory called: assignment
  • copy the csv-file containing your family's birth dates into it

In [ ]:
# assign the path to the csv-file to the variable 'path_to_csv'
path_to_csv = 'assignment/birth.csv'

In [ ]:
# open the csv-file for reading
# fp is a "file pointer" to the data payload of the file (text)
fp = open(path_to_csv, 'r')

In [ ]:
# read the contents of the file into a new variable, 
file_cont = fp.read()

# REMEMBER TO CLOSE the file (more critical when writing)
fp.close()

In [ ]:
# see what we got
file_cont

In [ ]:
type(file_cont)

Read file line-by-line


In [ ]:
fp = open(path_to_csv, 'r')

Exute the following cell repeatedly until you no longer get anything out of the file (Control-Enter will be useful)


In [ ]:
line = fp.readline()
print(line)

In [ ]:
fp.close()

Read the file into a list of lines


In [ ]:
fp = open(path_to_csv, 'r')
all_lines = fp.readlines()
fp.close()

In [ ]:
type(all_lines)

In [ ]:
all_lines  # show them

In [ ]:
type(all_lines[1])  # what type is the 2nd element of the list?

In [ ]:
all_lines[1]  # hi Dad!

Split a string at a character

Let's make a list of all birth dates. For this, we want to

  • loop over all lines, starting from the 2nd line (1st is the column names)
  • split each line on the comma (,)
    • this creates a list of length 3 for name, date and place
  • print the 2nd element of the split-list

In [ ]:
# test the split-method
all_lines[1].split(',')

In [ ]:
# loop from the 2nd element, to the end
# use the 'slice'-notation [1:], meaning "from index 1 to end"
for li in all_lines[1:]:
    split_line = li.split(',')
    print(split_line[1])

Strings can be sliced: they're lists of characters

Repeat the above, but now only print the third and fourth digits of the birth year!


In [ ]:
for li in all_lines[1:]:
    split_line = li.split(',')
    print(split_line[1][2:])  # NB: [1][2:]

Since split_line[1] is a string, split_line[1][2:] reads:

show the characters from the third element of the string split_line[1] to the end

Lists can be appended to

Starting with a list of values, add a new item (to the end) using the .append-method:


In [ ]:
my_list = ['apple', 'orange']
print('My list is', len(my_list), 'elements long.')

my_list.append('banana')
print('My list is', len(my_list), 'elements long.')
print(my_list)

Often it's useful to start with an empty list and append to it:


In [ ]:
new_list = []  # an empty list: nothing between the hard brackets
print('Before append:', new_list)
new_list.append(42)
print('After append:', new_list)

Is x in a list? Use the in-operator

In Python, we have a handy boolean operator for finding out whether an item exists in a list:


In [ ]:
print(my_list)  # ['apple', 'orange', 'banana']
print('orange' in my_list)
print('kiwi' in my_list)
print('Orange' in my_list)  # case-sensitive!