python language functions reading/writing files catching exceptions

45
Python language Functions Reading/writing files Catching exceptions

Upload: angel-arnold

Post on 29-Dec-2015

258 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Python language Functions Reading/writing files Catching exceptions

Python language

FunctionsReading/writing filesCatching exceptions

Page 2: Python language Functions Reading/writing files Catching exceptions

Function Definition

def function_name (arg1, arg2, …) : # arg means argument or parameter!body

# Sometimes we pass a known value for one of the arguments:def function_name (arg1, arg2=default2, arg3): # e.g., power (x, y=3)

body

Page 3: Python language Functions Reading/writing files Catching exceptions

Function with docsting

Page 4: Python language Functions Reading/writing files Catching exceptions

Function modifies a string

Page 5: Python language Functions Reading/writing files Catching exceptions

Pass arguments by position

Page 6: Python language Functions Reading/writing files Catching exceptions

Casting user’s entered value

Page 7: Python language Functions Reading/writing files Catching exceptions

Function traverses a string with a loop

Page 8: Python language Functions Reading/writing files Catching exceptions

Using datetime functions

• The age function uses the input function to get the birth year.• It then imports the datetime module• Gets the current year form the now () function.• Calculates the age, and returns it

Page 9: Python language Functions Reading/writing files Catching exceptions

Built in Numeric Functions

• abs(), divmod(), float(), hex(), long(), max(), min(), oct(), pow(), round()

# there are a lot more for trigonometry, etc.

• ‘none’ is a special data type for empty value– e.g., when a function does not return a value– It is used as a placeholder

Page 10: Python language Functions Reading/writing files Catching exceptions

Find maximum of any unknown set of arguments

• Notice that the function is called with different numbers of arguments. The * does the trick!

Page 11: Python language Functions Reading/writing files Catching exceptions

Defining a global variable

• Notice that calling the local variable outside of the function leads to error!

Page 12: Python language Functions Reading/writing files Catching exceptions

Assigning the returned value of a function to a variable

Page 13: Python language Functions Reading/writing files Catching exceptions

Tools in Arcpy are function!• Tools have name, which is similar to the tool’s label in ArcGIS

(without space), for example:– AddField for the Add Field tool

• The alias for a tool is not the same as its name or label.• It is a short version of it, for example:– ‘management’ is the alias for Data Management toolbox– Clip_management is the Clip tool in the Data Management

toolbox

Page 14: Python language Functions Reading/writing files Catching exceptions

Two ways to access a tool in ArcGIS

• All tools are available as function in Arcpy• Each tool (function) does a specific task

• To access a tool, we can:1. Call its corresponding function

arcpy.toolname_toolboxalias (arguments)

For example: call the Clip tool:>>> import arcpy>>> arcpy.env.workspace = “C:/Data”>>> arcpy.Clip_analysis (“stream.shp”, “study.shp”, “result.shp”)

Another example:>>> arcpy.env.workspace = “C:/Data/study.gdb”>>> arcpy.Buffer_analysis (“roads”, “buffer”, “100 METERS”)

Page 15: Python language Functions Reading/writing files Catching exceptions

Functions in ArcGIS – GetMessages()• When a tool is run in ArcGIS, messages write about

its success or failure

• To get the message, we use the following functions:

>>> arcpy.GetMessages ()>>> print arcpy.GetMessages (0) # 1st message>>> count = arcpy.GetMessageCount ()>>> print arcpy.GetMessage (count-1) # prints the last message

Page 16: Python language Functions Reading/writing files Catching exceptions

2. Tools are also in modules that match the toolbox alias name

arcpy.toolboxalias.toolname (arguments)• For example:

>>> import arcpy>>> arcpy.env.workspace = “C:/Data”>>> arcpy.analysis.Clip (“stream.shp”, “study.shp”, “result.shp”)

These two methods are equivalent! It depends on our preference.

Page 17: Python language Functions Reading/writing files Catching exceptions

Other examples>>> import arcpy>>> arcpy.env.workspace = “C:/Data”>>> infc = “streams.shp” # fc stands for feature class>>> clipfc = “study.shp”>>> outfc = “result.shp”>>> count = arcpy.GetCount_management (infc, clipfc, outfc)>>> print count # prints the count for streams>>> result = arcpy.analysis.Clip (infc, clipfc, outfc)>>> print result # prints an object# will print the path to the result shape file, i.e., : C:/Data/result.shp

Page 18: Python language Functions Reading/writing files Catching exceptions
Page 19: Python language Functions Reading/writing files Catching exceptions

Filesystem• Filesystem refers to naming, creating, moving, or referring to

files.

• Depends on the operating system.

• Pathname: String that refers to the location of the file in a directory

• Filesystem in all operating systems is a tree structure, made of a root (disk), directory, subdirectory, and its branches.

• In Windows, the \ character is used to separate the file or directory names from each other. – There is a separate root for each drive (A:\, C:\, D:\)– For example: C:\myDirectory\myfile

Page 20: Python language Functions Reading/writing files Catching exceptions

Paths in Python• In Python, backslash (\) is used for escape.• For example, \n and \t for line feed and tab

• Therefore, we avoid using \ in Python paths. Instead:• We use forward slash;

C:/Data/Exercise01.txt

• Or, we use double backslash (\\)C:\\Data\\Exercise01.txt

• OR, use a string litteral: #put ‘r’ before the string. r means raw stringr”C:\Data\Exercise01.txt”

• Paths are stored as string in Python!• For example, the following assigns the path to a shape file as a string for the

inputfc variable (fc is feature class in ArcGIS)>>> Inputfc = “C:/Data/lakes.shp”

Page 21: Python language Functions Reading/writing files Catching exceptions

Absolute path vs. relative path• Absolute path is the exact address of the file in the filesystem,

starting from the root.C:\Geoinformatics\myFile.txtA:\Courses\Python\Programming.html

• Relative path writes it with respect to another point in the file system

Python\Functions\map.txt

• We can either append a relative path to an existing absolute path.

• Or, we can implicitly reference the current working directory where a Python program may consider to be during an execution.

Page 22: Python language Functions Reading/writing files Catching exceptions

Current working directory - cwd

• Python knows the current directory of the file it is working on (just like you know when you work on a file that you open from a directory).

• This directory is called the ‘current working directory” or cwd for a program.

• Do the following to get the cwd of Python on your computer

Page 23: Python language Functions Reading/writing files Catching exceptions

Opening files in read mode

Page 24: Python language Functions Reading/writing files Catching exceptions

Opening a file in the write mode• We pass ‘w’ instead of ‘r’ in the 2nd argument• This will first erase data in the file before writing.• NOTE: If we want to append to the file, use ‘a’ instead of ‘w’.

Page 25: Python language Functions Reading/writing files Catching exceptions

Open File - example

>>> f = open ("C:/Data/mytext.txt", "w")>>> f.write ("GIS")

>>> f = open ("C:/Data/mytext.txt", "r")>>> f.read()'GIS‘

Page 26: Python language Functions Reading/writing files Catching exceptions

Read the number of lines in a file

• Assume the multi_line.txt file has five words written in five lines

Page 27: Python language Functions Reading/writing files Catching exceptions

Screen input/outputInput () is a built-in method to prompt for input; returns a string

Page 28: Python language Functions Reading/writing files Catching exceptions
Page 29: Python language Functions Reading/writing files Catching exceptions

Throwing exceptions (Error handling)• Are used to handle unusual circumstances (e.g.,

errors) encountered during the execution of the program.

• We have to realize that errors will happen, and write code to detect and handle them.

• This is done by returning a status value by a function to indicate whether a function was executed successfully or not

Page 30: Python language Functions Reading/writing files Catching exceptions

Raising (throwing) an exceptiontry :

# if there is no problem, do your operations here# …

except :# execute this block if there is any exception (problem)# handle possible problem here

else :# If there is no exception, execute this block# …

finally :# this always will execute. # used to manage resources (e.g., # close files).

Page 31: Python language Functions Reading/writing files Catching exceptions

General try/except

try: statements # Run this main action first

except name1: statements # Run if name1 is raised during the try block

except (name2, name3): statements # Run if any of these exceptions occur

except:statements # Run for all (other) exceptions raised

else: statements # Run if no exception was raised during try block

Page 32: Python language Functions Reading/writing files Catching exceptions

try :body # is executed first. # If successful (no error), the else block is executed, and try is finished# If exception is thrown in try, the 1st except clause is searched

except exception_type1 as var1 : # if this clause matches the error,# the error is assigned to the variable var1 after the exception type,# and the exception code below the associated type is executedexception code1 # handle the raised exception, otherwise:

except exception_type2 as var2 : # comes to here if the first except clause did not match.exception code2 # this may process if it matches

… # and so onelse : # if there is no error, come here, this is optional, and rarely used

else_bodyfinally : # optional. If it exists, it always executes

finally_body # clean up by closing files or resetting variables

Page 33: Python language Functions Reading/writing files Catching exceptions

Common exception errors and examples

• IOError If the file cannot be opened or read.print (“Error while reading the file”)

• ImportError If python cannot find the moduleprint (“no module found”)

• ValueError Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value

print (“non-numeric data found”)• KeyboardInterrupt Raised when the user hits the interrupt key

(normally Control-C or Delete)print (“you cancelled the operation”)

• EOFError Raised when one of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF) without reading any data

print (“end of file”)

Page 34: Python language Functions Reading/writing files Catching exceptions

Handle ValueError

Page 35: Python language Functions Reading/writing files Catching exceptions

Assign exception to variable

Page 36: Python language Functions Reading/writing files Catching exceptions

• Example: Define a function to get a number from a user.• Convert it into float• If it cannot be converted to float, send a message

Handle ValueError …

Page 37: Python language Functions Reading/writing files Catching exceptions

Exception is an object (as in OOP)• Exceptions can be raised by any function and given to a variable>>> list = [2, 4, 6]>>> x = list[2]>>> print x6

>>> x = list[4] # this raises the ‘list index out of range’ errorTraceback (most recent call last): File "<interactive input>", line 1, in <module>IndexError: list index out of range

• The error is handled by Python by writing the above message, which in this case terminates the program because there is no exception handler!

Page 38: Python language Functions Reading/writing files Catching exceptions

Catching when knowing the type of error

Page 39: Python language Functions Reading/writing files Catching exceptions

Catching multiple error types

Page 40: Python language Functions Reading/writing files Catching exceptions

IOError

Page 41: Python language Functions Reading/writing files Catching exceptions

• We use try/except for quality assurance (QA)Handle opening file issues

Page 42: Python language Functions Reading/writing files Catching exceptions

IOError …

Page 43: Python language Functions Reading/writing files Catching exceptions

IOError …

Page 44: Python language Functions Reading/writing files Catching exceptions

Catch all exception types

Page 45: Python language Functions Reading/writing files Catching exceptions

Python programs

• Up until now you have interactively used Pythonwin to communicate with the Python interpreter.

• A set of Python statements saved in a file constitutes a Python program or script.

• The program usually has a controlling function that can be called to run the program.