Advanced Python
In-Class Exercise Solutions, Session 1
COMMAND LINE |
|
Ex. 1.1 | Open a Command Prompt (Windows) or a Terminal window (Mac) and follow the steps in the assignment. |
ARGPARSE MODULE |
|
Ex. 1.2 | Use argparse to accept a required argument from the command line. |
Starting with the below code, use parser.add_argument() to add argument 'name'. The argument should expect either -n or --name as identifier at the command line. Include a required=True argument to make the argument required. Call .parse_args() on the parser object. The program should then print the value of the 'name' argument. Test the program by running it from a Terminal or Command Prompt. Then, test it a second time by omitting the argument, and note that the required=True causes the program to output an error message. |
|
import argparse
import os
import sys
parser = argparse.ArgumentParser(
prog=os.path.basename(sys.argv[0]))
parser.add_argument('-n', '--name', required=True)
args = parser.parse_args()
print(args.name)
|
|
Ex. 1.3 | View the help message. Starting with the above solution, add a description= argument to ArgumentParser; the value should be a string explaining what the program does. |
Call the same program with the --help or -h flag. Note the automated output explaining how the program works. |
|
import argparse
import os
import sys
parser = argparse.ArgumentParser(
prog=os.path.basename(sys.argv[0]),
description='prints your name!')
parser.add_argument('-n', '--name', required=True)
args = parser.parse_args()
print(args.name)
|
|
Ex. 1.4 | Add an argument restricted to specific choices. |
Continue the same program; add an argument 'color' with the choices= argument. Restrict the choices to blue, green or red. Print the value of the color argument. Call the program with a --color argument and one of the valid colors; then call the program with --color and an invalid choice; note that it is rejected. |
|
import argparse
import os
import sys
parser = argparse.ArgumentParser(
prog=os.path.basename(sys.argv[0]),
description='prints your name!')
parser.add_argument('-n', '--name', required=True)
parser.add_argument('-c', '--color', choices=['red', 'blue', 'green'])
args = parser.parse_args()
print(args.name)
print(args.color)
|
|
Ex. 1.5 | Add an argument allowing multiple values. |
Continue the same program; add argument --cities and add the nargs='+' argument to allow multiple values. Call the program with the --cities argument and a couple of city values. |
|
import argparse
import os
import sys
parser = argparse.ArgumentParser(
prog=os.path.basename(sys.argv[0]),
description='prints your name!')
parser.add_argument('-n', '--name', required=True)
parser.add_argument('-c', '--color', choices=['red', 'blue', 'green'])
parser.add_argument('-x', '--cities', nargs='+')
args = parser.parse_args()
print(args.name)
print(args.color)
print(args.cities)
|
|
CSV MODULE |
|
Ex. 1.6 | Use csv.reader to read a file. Take the following steps, testing as you go: |
|
|
import csv
fh = open('../revenue.csv') # 'file' object
reader = csv.reader(fh) # csv.reader object
next(reader) # advances pointer past 1st line header
fsum = 0.0 # float, 0.0
for row in reader: # list, ["Haddad's", 'PA', '239.5']
fval = float(row[-1]) # float, 239.5
fsum = fsum + fval # float, 239.5
print(fsum)
|
|
Ex. 1.7 | Use csv.reader to read the header of a file. Using the code solution from the previous exercise, before the for block, use a call to next(reader) to retrieve and print the header of the file, noting that the loop then begins on the next line of the file. |
import csv
fh = open('../revenue.csv') # 'file' object
reader = csv.reader(fh) # csv.reader object
header = next(reader)
print(header)
fsum = 0.0 # float, 0.0
for row in reader: # list, ["Haddad's", 'PA', '239.5']
fval = floatrow[-1]) # float, 239.5
fsum = fsum + fval # float, 239.5
print(fsum)
|
|
Ex. 1.8 | Write individual rows to a CSV file using csv.writer. Take the following steps, testing as you go: |
|
|
import csv
header = ['name', 'address', 'state', 'zip'] # list, ['name', 'address' ... ]
row1 = ['Joe', '123 Main', 'CA', '91603'] # list, ['Joe', '123 Main' ... ]
row2 = ['Marie', '234 Camarino', 'NJ', '92325'] # list, ['Marie', '234 Camarino' ... ]
fname = '../newfile.csv' # str, '../newfile.csv'
wfh = open(fname, 'w', newline='') # 'file' object
writer = csv.writer(wfh) # csv.writer object
writer.writerow(row1) # int, 23 (# of bytes written, not used)
writer.writerow(row2) # int, 29
wfh.close()
|
|
Ex. 1.9 | Write multiple rows to a CSV file using csv.writer. Follow the same steps as above, but use .writerows() to write the entire list of lists to the file. Close the file, then look for newfile2.csv in the session directory. |
rows = [
[ 'date', 'temp', 'wind' ],
[ '2020-06-13', '78.3', '6' ],
[ '2020-06-14', '77.0', '8' ],
] # list
fname = '../newfile2.csv' # str, '../newfile2.csv'
wfh = open(fname, 'w', newline='') # 'file' object
writer = csv.writer(wfh) # csv.writer object
writer.writerows(rows)
wfh.close()
|
|
Ex. 1.10 | Use csv.writer to selectively write rows to a CSV. Loop through the list of lists and write only the US rows to the file. Also write the header as the first row. Close the file, then look for newfile3.csv in the session directory. |
rows = [
[ 'company', 'state/province', 'country' ],
[ 'Acme', 'Caliornia', 'US' ],
[ 'Bento', 'Toledo', 'SP' ],
[ 'OuiOui', 'Bourges', 'FR' ],
[ 'Beta', 'New York', 'US' ]
] # list
fname = '../newfile3.csv' # str, '../newfile3.csv'
wfh = open(fname, 'w', newline='') # 'file' object
writer = csv.writer(wfh) # csv.writer object
writer.writerow(rows[0]) # int, 32 (bytes written)
for row in rows[1:]: # list, ['Acme', 'Caliornia', 'US']
if row[2] == 'US': # bool, True
writer.writerow(row) # int, 19
wfh.close()
|
|
Ex. 1.11 | Use csv.writer to selectively write columns to a CSV. Loop through the list of lists and write only the company and country columns to the file. Include the header. Close the file, then look for newfile4.csv in the session directory. |
rows = [
[ 'company', 'state/province', 'country' ],
[ 'Acme', 'Caliornia', 'US' ],
[ 'Bento', 'Toledo', 'SP' ],
[ 'OuiOui', 'Bourges', 'FR' ],
[ 'Beta', 'New York', 'US' ]
] # list
fname = '../newfile4.csv' # str, '../newfile4.csv'
wfh = open(fname, 'w', newline='') # 'file' object
writer = csv.writer(wfh) # csv.writer object
header_row = rows[0] # list, ['company', 'state/province', ...]
# writes ['company', 'country']
writer.writerow([ header_row[0], header_row[2] ]) # int, 17
for row in rows[1:]: # list, ['Acme', 'California', 'US']
sel_fields = [ row[0], row[2] ] # list, ['Acme', 'US']
writer.writerow(sel_fields) # int, 9
wfh.close()
|
|
Ex. 1.12 | Use csv.DictReader to read a file line-by-line, each line a dict. |
As you loop through the DictReader object, print each row dict. |
|
import csv
fname = '../revenue.csv'
fh = open(fname)
dreader = csv.DictReader(fh)
for row in dreader:
print(row)
|
|
Ex. 1.13 | Use csv.DictReader to read the header line of a file. |
Continue the previous solution -- read and print the file's headers using the .fieldnames attribute. |
|
import csv
fname = '../revenue.csv'
fh = open(fname)
dreader = csv.DictReader(fh)
print(dreader.fieldnames)
|
|
Ex. 1.14 | Use csv.DictWriter to write a header to a file. |
Starting with the following filename and headers list, open the file for writing, then instantiate a csv.DictWriter object with the file object and headers; use the .writeheader() argument to write the header row. Make sure to close the write filehandle with .close() (make sure to include the parentheses!) after all writing is done. Run the program, then check the file to see that it has been created and contains the headers |
|
import csv
filename = 'newfile.csv'
headers = ['fname', 'lname', 'state']
wfh = open(filename, 'w')
dwriter = csv.DictWriter(wfh, headers)
dwriter.writeheader()
wfh.close()
|
|
Ex. 1.15 | Use csv.DictWriter to write lines to a file. |
Continuing from the previous solution (below, with some data line dictionaries added), use .writerow() to write the dicts to the file. |
|
import csv
filename = 'newfile.csv'
headers = ['fname', 'lname', 'state']
data_lines = [
{ 'fname': 'Joe', 'lname': 'Wilson', 'state': 'CA' },
{ 'fname': 'Mike', 'lname': 'Sanchez', 'state': 'NY' },
{ 'fname': 'Marie', 'lname': 'Obubwe', 'state': 'NJ' },
]
wfh = open(filename, 'w')
dwriter = csv.DictWriter(wfh, headers)
dwriter.writeheader()
for drow in data_lines:
dwriter.writerow(drow)
wfh.close()
|
|
Ex. 1.16 | Create a dictionary by zipping up two lists. |
Given the following list of headers and data row, use dict(zip()) with the two lists to zip the two lists together into a list of 2-item tuples, and convert them to a dict. Print the dict. |
|
headers = ['fname', 'lname', 'state']
data = ['Joe', 'Wilson', 'CA']
d = dict(zip(headers, data))
print(d)
|
|