I719 Fundamentals of Python/lecture3

From ICO wiki
Revision as of 20:21, 17 February 2017 by Eroman (talk | contribs) (add lecture notes)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Lecture 3

Lets review! - lists - dictionaries - strings - comparison operators

Command line arguments

The standard library has sys which give us access to the command line arguments executed.

import sys

if '-h' in sys.argv or '--help' in sys.argv:
    print('Sorry I can\'t help you :(')

But argparse from the standard library is much easier if we want to use the commandline arguments.

File opening

f = open(filename)
# interact with the file

# is the same as
with open(filename) as f:
    # interact with the file

here is an example of a script that opens a file, and print all lines in the file. The file name is specified as the first command line argument

Print all lines in file
import argparse

def main():
    parser = argparse.ArgumentParser()
    args = parser.parse_args()
    text_file = open(args.file_name)
    for line in text_file:
        cleaned_line = line.strip() # Remove newline, i.e. '\n' or '\r\n'

if __name__ == '__main__':


Print out a dictionary with words and the number of occurences of the word.

Example output:

{'Apple': 10, 'Bananan': 1}

How to count words in a list of words

>>> words = ['hello', 'hi', 'hello']
>>> wc = {}
>>> for word in words:
...     if word in wc:
...         wc[word] = wc[word] + 1
...     else:
...         wc[word] = 1
>>> wc
{'hello': 2, 'hi': 1}

Task 2

Make a new csv file and save it, where the age become year born.


convert input csv to output csv
import argparse
import csv

def convert_age_in_csv(data_in, data_out):
    reader = csv.reader(data_in)
    writer = csv.writer(data_out)
    for row in reader:
        name = row[0].strip()
        age = int(row[1])
        year_born = 2017 - age
        writer.writerow([name, year_born])

def main():
    parser = argparse.ArgumentParser()
    args = parser.parse_args()

    with open(args.data_in, 'r') as data_in:
        with open(args.data_out, 'w') as data_out:
            convert_age_in_csv(data_in, data_out)

if __name__ == '__main__':

How to execute

python3 csvconverter.py input.csv output.csv