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)
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()
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!
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])
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
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)
In [ ]:
print(my_list) # ['apple', 'orange', 'banana']
print('orange' in my_list)
print('kiwi' in my_list)
print('Orange' in my_list) # case-sensitive!