Download presentation
Presentation is loading. Please wait.
Published byBuck McDowell Modified over 8 years ago
1
Today… Strings: –String Methods Demo. Raising Exceptions. os Module Winter 2016CISC101 - Prof. McLeod1
2
Help With String Methods More detail in section 4.7.1 of the Python Standard Library help docs. Or look up “string” then “methods” in the index. CISC101 - Prof. McLeod2Winter 2016
3
CISC101 - Prof. McLeod3 Demo of String Methods Starts with the tuple or list returns methods, then looks at how you could analyze larger amounts of text. See StringMethodsDemo.py This demo did not work with a very large amount of text, but the same techniques could easily be applied to much larger documents – newspapers, transcribed speeches, books, texts, emails,… Python text manipulation code is very compact and can be quite powerful. Winter 2016
4
Could You Write a String Method? Knowing only: –ASCII character codes –How to loop through a string –String operators –And the len(), ord() and chr() BIFS Could you write all of the string methods yourself? Sure!! Winter 2016CISC101 - Prof. McLeod4
5
You Can Write These! But, since we don’t know how to extend the string class in order to add methods to it, let’s just write a function instead. Imitate something like.swapcase(), for example: Write a function called upperLower (?) that changes upper case letters to lower case and lower case letters to upper case. See TestUpperLower.py Winter 2016CISC101 - Prof. McLeod5
6
Raising Exceptions Sometimes a function just has to fail. (Like the.index() method when the string cannot be found.) Until now: def aFunction(aParam) : if aParam == "fail" : print("I am sorry, but I cannot continue!") return else : return len(aParam) Winter 2016CISC101 - Prof. McLeod6
7
Raising Exceptions, Cont. Assuming that the function cannot repair the problem, it just has to exit. This is kind of lame: –What happens if the invoking function is expecting a return value? –It is not wise and often not even possible to simply return some sort of magic error code that can be used by the invoking function to detect a problem. Do different functions have different error codes? –How else can the invoking function know the function that it just called could not do its job? Winter 2016CISC101 - Prof. McLeod7
8
Raising Exceptions, Cont. The exception mechanism is a much better way of allowing a function to “abort”: –No worries about the function returning something. In fact the whole return thing is irrelevant – the function never gets to return anything and the statement expecting the return value in the invoking function never has a chance to finish. –The existence of an error condition is made very clear to the invoking function. –The invoking function can catch the exception – maybe it will be able to fix the problem? –This mechanism is an expected part of most modern programming languages. Winter 2016CISC101 - Prof. McLeod8
9
Raising Exceptions, Cont. Do this instead: def aFunction(aParam) : if aParam == "fail" : raise ValueError("The fail argument!") else : return len(aParam) Winter 2016CISC101 - Prof. McLeod9
10
Raising Exceptions, Cont. raise ValueError("The fail argument!") The raise keyword “raises” or “throws” the exception. The function immediately stops after the raise command is executed. You must raise an exception object – typically you would use one already defined in Python. ValueError is a good general purpose exception. And, supply a relevant message to the exception as a string literal. Winter 2016CISC101 - Prof. McLeod10
11
Raising Exceptions, Cont. Of course if the exception is not caught, we see: Traceback (most recent call last): File "C:/Users/Alan/Teaching/CISC101/2016Winter/Code/SecondHalf/FailingFu nction.py", line 10, in main() File "C:/Users/Alan/Teaching/CISC101/2016Winter/Code/SecondHalf/FailingFu nction.py", line 8, in main print(aFunction("fail")) File "C:/Users/Alan/Teaching/CISC101/2016Winter/Code/SecondHalf/FailingFu nction.py", line 3, in aFunction raise ValueError("The fail argument!") ValueError: The fail argument! Winter 2016CISC101 - Prof. McLeod11
12
Raising Exceptions, Cont. If we don’t want to see all that, then the function needs to be invoked in a try/except construct. Which we know how to do… Even if you cannot fix the problem at least the try/except structure gives you a chance to exit your program gracefully, without the user seeing all the red stuff! Winter 2016CISC101 - Prof. McLeod12
13
Raising Exceptions, Cont. You can have as many raise statements inside a function as you need – use the same exception, but provide different messages, so the user of your function has a better idea of what the specific error is. In assignment 4, you raise a ValueError, but you also need to be prepared to catch the OSError exception raised by the open() BIF. Winter 2016CISC101 - Prof. McLeod13
14
File I/O Problems These often result in exceptions: –File not found. –File corrupted and cannot be read. –Write operation fails before file is closed. –Folder not found. –No permission to read folder or file. –No permission to write folder or file. –etc. Sometimes these kinds of errors can be prevented – which is always preferable to catching exceptions. Winter 2016CISC101 - Prof. McLeod14
15
os Module This module is very helpful if you have to do quite a bit of work with files and folders. Such as: –Does a file exist already? Is it empty? –Does a folder exist. –What are folder and/or file permissions? Can they be changed? Basically the module provides an interface to your OS. CISC101 - Prof. McLeod15Winter 2016
16
CISC101 - Prof. McLeod16 os Module, Cont. Behind the scenes, this module loads a module for your particular operating system. So regardless of your OS, you import os… See section 16.1 in the Python Library Reference. Lots of goodies, particularly file system utilities. Here’s a selection of file-related functions: Winter 2016
17
CISC101 - Prof. McLeod17 os Module, Cont. remove() – deletes a file rename() – renames a file walk() – generates filenames in a directory tree (a generator object) chdir() – change working directory chroot() – change root directory of current process listdir() – list files and folders in directory getcwd() – gets current working directory mkdir() – creates directory Winter 2016
18
CISC101 - Prof. McLeod18 os Module, Cont. rmdir() – removes directory access() – verify permission modes (2 parameters) chmod() – change permission modes In os.path: basename() – returns name of file dirname() – returns name of directory join() – joins directory and filename split() – returns both as tuple splitext() – returns filename and extension as tuple Winter 2016
19
CISC101 - Prof. McLeod19 os Module, Cont. In os.path, Cont: getatime() – returns last file access time getctime() – returns file creation time getmtime() – returns file modification time getsize() – returns file size in bytes exists() – does file or directory name exist? isdir() – is this a directory name and does it exist? isfile() – is this a file and does it exist? Winter 2016
20
CISC101 - Prof. McLeod20 os Module, Cont. Demo program – see LargeFileSearch.py Uses the os.walk function and several others from the os and os.path modules. Winter 2016
21
CISC101 - Prof. McLeod21 os Module, Cont. Python already has an exec() BIF that allows you to run external python code from within your program. The os module also has many commands that allow you to run other non-python programs from within your program. For example, os.system() allows you to run a system command (a DOS command, for example). Winter 2016
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.