Exam Notes Section 3

shbang

shbang tells the interpretor how to execute this file.
Invoking python3 before the file is not needed with shbang.
i.e python3 test.py // not needed

Example:

#!/usr/bin/env python3

python code

Command Line Arguments

SYS module

sys module can be used to accept command line arguments to a program.
sys.argv returns a list of arguments passed to the program
– sys.argv[0] – always returns program name
– sys.argv[1] – gives 1st argument

Note: if you pass 2 arguments to the program then len(sys.argv) will be 3 as 0 element is always the program name.

Argparse module

argparse module was introduced in pyhton3 and is a enhanced version of sys module.
argparse makes a help menu with the added arguments, it can also accept True/False for options.

Actions:
store – stores the value in argument variable
store_true – stores true values
store_false – store false values
append – appends the arguments to a list
count – counts the number of arguments (-vvv)
version – can be used to retuen the version of the program

Type:
int – accept only integers
str – accept only strings
open – use to return a filedescription to open file

import argparse
parser = argparse.ArgumentParser()  // initialize parser
parser.add_argument("echo")  // add positional argument (default data type is string, action is store)
parser.add_argument("--verbose", help="increase output verbosity",
                    action="store_true")  // add a optional argument
args = parser.parse_args() // parses arguments and returns a dict like object
if args.verbose:
    print("verbosity turned on")
print(args.echo)

Files

Check if file exists

os modue can used to handle files on the system.
os.path.isfile : Checks if file exists on the given location, Also follows symbolic links
os.path.exists : Check if file or folder exists on the given location, Also returns False for broken symbolic link

Example:

import os
if os.path.isfile('test.txt'):
    file exists and do something

Open files for reading and writing

open function can be used read and write data to/from files
– return a file handle
– can be looped over to get data
!!! if not using with then need to close the file handle by fh.close() !!

Example:

with open('test.txt') as fh:
    do something

Lists

lists are array like objects in python. items can be added and removed from the list.
– list.append(x) : appends x to the list
– list.remove(x) : removes x from the list
– list.sort() : sorts the list in ascending order
– list.reverse(): sorts a sorted list in reverse order