The third quiz will cover the following topics:
File I/O
Data Manipulation
The quiz will consist of definitions, short answers, code evaluation, translation, and programming sections.
Below are examples of the type of questions that may be asked on the quiz. It is meant to be representative, rather than exhaustive (ie. there may be questions that show up on the quiz that are not shown below).
Briefly define the following terms.
File Handle
Text File
Binary File
CSV
JSON
IOError
Write some Python code that does each of the following:
Reads all the contents of a file into a single string.
Reads all the contents of a file into a list of strings.
Prints out the contents of a file line-by-line.
Lists the contents of a directory.
Write all the items in a list of strings to a file.
Write all the items in a dictionary to a file.
What are the four basic operations you can perform on a file (handle)?
Why should you close a file after opening it?
What are some reasons why an open would fail?
What are some advantages to using the csv
Python module for parsing
comma-separated-values, rather than simplying doing str.split
?
Given the following turtles.csv
file:
Name,Color,Weapon,Species
Leonardo,blue,katana,turtle
Donatello,purple,bo,turtle
Raphael,red,sai,turtle
Michelangelo,orange,nunchucks,turtle
Splinter,brown,staff,rat
Casey Jones,white,hockey stick,human
April O'Neil,yellow,microphone,human
Shredder,purple,armor,human
What is the result of the following Python code:
c = {}
for index, line in enumerate(open('turtles.csv')):
if not index:
continue
d = line.strip().split(',')
s = d[-1]
c[s] = c.get(s, 0) + 1
for k, v in sorted(c.items()):
print '{:8}: {}'.format(k, v)
Given the turtles.csv
files and code above, modify the code to use the
csv
module instead of manually parsing the csv
data.
Write a Python program that lets you look up a value in a CSV file by row number and column name.
def lookup_csv_value(csv_path, row_number, column_name):
''' Return the value in the file `csv_path` at the `row_number` for
the column `column_name`.
'''
# Examples using 'turtles.csv' file above
>>> lookup_csv_value('turtles.csv', 0, 'Name')
'Leonardo'
>>> lookup_csv_value('turtles.csv', 3, 'Weapon')
'staff'
Given the following URL:
http://xavier.h4x0r.space:9097/services.json
Using requests
to fetch the JSON data and examine the data to count
all the different opsys
values from the services listed in the catalog:
def count_opsys(url):
''' Return a dictionary containing the counts of all the different
`opsys` in the JSON data '''
>>> count_opsys('http://xavier.h4x0r.space:9097/services.json')
{u'Linux': 4}
Note: If the URL above does not work, try
http://www3.nd.edu/~pbui/teaching/cdt.30010.fa16/static/json/services.json
.