Monday, 16 October 2017

Try, Except and Global

We've seen errors in the output of programs on this blog. But what if we wanted to do something that might result in an error but we don't want it to stop the program completely?
The Python keywords try and except are used to deal with exceptions (a sort of error) in a graceful way so the program doesn't simply crash.

The keyword global tells Python that a variable is used both within a function and beyond it in the wider program.
When variables are used inside a function, Python assumes that those variables are specific to that function, even if other variables in the program outside that function share the same name.
The global keyword overrides this assumption and makes it clear to Python (and anyone reading it) that this is the same variable used across the whole program.
Here is a program to demonstrate:

#!/usr/bin/python3
import os
import os.path
 
def sesame():
    contentlist = os.listdir()
    filelist = []
    for item in contentlist:
        if os.path.isfile(item):
            filelist.append(item)
    print (filelist)
    filename = input('Please enter filename: ')
    try:
        handle = open(filename, 'r')
        for line in handle:
            print(line, end='')
        handle.close()
    except:
        print ('File not found.')
        return
 
def finddir():
    global currentdir
    global dirname
    print ('start finddir(), current directory is:', currentdir)
    contentlist = os.listdir()
    dirlist = []
    for item in contentlist:
        if os.path.isdir(item):
            dirlist.append(item)
    print (dirlist)
    dirname = input('Please enter subdirectory or hit return to use this one: ')
    try:
        tempdir = currentdir+dirname+'\\'
        os.chdir(tempdir)
        currentdir = tempdir # This won't happen if previous line fails
    except:
        print('Sorry, not valid directory')
 
print ('Program to find and display contents of file')
global currentdir
global dirname
currentdir = os.getcwd()
dirname = 'x'
print ('Current directory is ', currentdir)
dirchoice = input('Keep current directory (Y/N)? ')
dirchoice = dirchoice.lower()
if dirchoice == 'n':
    currentdir = 'C:\\'
    os.chdir(currentdir)
    while dirname !='':
        finddir()
sesame()

So there are a number of things I should point out:
  • Here there are two different user-defined functions (finddir() and sesame()). Strictly speaking they did not need to be functions but I thought it would be good practice. 
  • Both functions use try...except... to attempt to open files or directories. 
  • The variables currentdir and dirname are used both in the main program and also in the finddir() function. The global statements for each makes this clear. 
  • As mentioned in a previous post, we are importing two modules: os and os.path, both of which contain useful functions that help in dealing with files, folders and paths:
    • os.listdir() returns a list of the contents of a directory/folder. If no path is given as an argument, it lists the contents of the current directory. 
    • os.path.isfile(filename) checks whether a given object or entity is a file
    • os.path.isdir(filename) checks whether a given object is a directory
    • os.chdir(path) changes the current working directory to the given path
    • os.getcwd() returns the path of the current working directory

No comments:

Post a Comment