Advanced Python
In-Class Exercises, Session 1

COMMAND LINE

Ex. 1.1 Open a Command Prompt (Windows) or a Terminal window (Mac).

  • (Unix only) Use pwd to see the "present working directory"
  • Use ls (Mac) or dir (Windows) to see a listing of the files and directories in this directory
  • Use cd to move into a directory you see listed in the present working directory (for example cd Downloads)
  • Use cd .. to move into the "parent" directory of the one you are in (this will take you back to the parent of Downlaods
  • Use cd /Users/[yourhomedir]/Desktop to move into the Desktop directory
  • Use cd ../Downloads to move from the Desktop directory to the Downloads directory
  • Use cd (Mac) or cd %HOMEPATH% (Windows) to move back into the home directory

 

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]))
Sample Run (note that the '%' represents your command prompt - yours will look different).
% python inclass_ex.py --name David
David
%  python inclass_ex.py
usage: inclass_ex.py [-h] -n NAME
inclass_ex.py: error: the following arguments are required: -n/--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]))


parser.add_argument('-n', '--name', required=True)

args = parser.parse_args()

print(args.name)
Sample program run:
% python inclass_ex.py --help
usage: inclass_ex.py [-h] -n NAME

prints your name!

options:
  -h, --help            show this help message and exit
  -n NAME, --name 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)

args = parser.parse_args()

print(args.name)
Sample program run:
% python inclass_ex.py --name David --color red
David
red
% python inclass_ex.py --name David --color purple
usage: inclass_ex.py [-h] -n NAME [-c {red,blue,green}]
inclass_ex.py: error: argument -c/--color: invalid choice: 'purple' (choose from 'red', 'blue', 'green')
%
 
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'])

args = parser.parse_args()

print(args.name)
print(args.color)
Sample program run:
% python inclass_ex.py --name David --color red --cities Chicago 'New York'
David
red
['Chicago', 'New York']
%
 

CSV MODULE

Ex. 1.6 Use csv.reader to read a file. Take the following steps, testing as you go:

  1. Open a file and pass the file object to csv.reader()
  2. Loop through the reader object line by line, printing each line. Note the type of the object representing each row.
  3. Subscript the float value from each list and convert to float.
  4. Initialize a float variable 0.0 at the top and add each float value to it inside the loop, producing a sum.

import csv

fh = open('../revenue.csv')
 
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

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:

  1. Open a file for writing and pass the filehandle to csv.writer() (when opening the file for writing, include the newline='' argument to open() so newlines will be written properly).
  2. Use .writerow() on the writer object to write each list to the file, starting with the header list.
  3. Close the file, then open and view newfile.csv in the session directory.

import csv

header = ['name', 'address', 'state', 'zip']

row1 = ['Joe', '123 Main', 'CA', '91603']
row2 = ['Marie', '234 Camarino', 'NJ', '92325']

fname = '../newfile.csv'     # a new file, or replacing old if exists

wfh = open(fname, 'w', newline='')
 
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' ],
       ]

fname = '../newfile2.csv'

wfh = open(fname, 'w', newline='')

writer = csv.writer(wfh)
 
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' ]
       ]

fname = '../newfile3.csv'

wfh = open(fname, 'w', newline='')
writer = csv.writer(wfh)
 
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' ]
       ]

fname = '../newfile4.csv'

wfh = open(fname, 'w', newline='')
writer = csv.writer(wfh)
 
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)
Expected Output:
{'company': "Haddad's, Inc.", 'state': 'PA', 'price': '239.5'}
{'company': 'Westfield', 'state': 'NJ', 'price': '53.9'}
{'company': 'The Store', 'state': 'NJ', 'price': '211.5'}
{'company': "Hipster's", 'state': 'NY', 'price': '11.98'}
{'company': 'Dothraki Fashions', 'state': 'NY', 'price': '5.98'}
{'company': "Awful's", 'state': 'PA', 'price': '23.95'}
{'company': 'The Clothiers', 'state': 'NY', 'price': '115.2'}
 
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)
Expected Output:
['company', 'state', 'price']
 
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']
After running, the file newfile.csv in the parent directory should have the following text:
fname,lname,state
 
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()

wfh.close()
After running, the file newfile.csv in the parent directory should have the following text:
fname,lname,state
Joe,Wilson,CA
Mike,Sanchez,NY
Marie,Obubwe,NJ
 
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']
Expected Output:
{'fname': 'Joe', 'lname': 'Wilson', 'state': 'CA'}
 
[pr]