Send Close Add comments: (status displays here)
Got it!  This site "www.robinsnyder.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.  Note: This appears on each machine/browser from which this site is accessed.
Python: With statement
by RS  admin@robinsnyder.com : 1024 x 640


1. Python: With statement
Python has a with statement.

The Python with statement abstracts the try except finally construct to allow a cleaner way to do operations but get control of exception handling with final processing - with or without raised error.

2. Reading a file
One way to open and read a file in Python is as follows.

Here is the Python code [#1]


3. Examples of input and output
Here are some examples of input and output for the above program code.

Here is an example input.

For the above example input, here is the expected output.


4. Try statement
The with helps clean up the code when error handling is needed. Consider the following way in which files are often process.d

Here is the Python code [#2]


5. Examples of input and output
Here are some examples of input and output for the above program code.

Here is an example input.

For the above example input, here is the expected output.


6. With statement
Here is the above program using the with statement.

Here is the Python code [#3]

Note that the close is not needed as it is called automatically.

7. Examples of input and output
Here are some examples of input and output for the above program code.

Here is an example input.

For the above example input, here is the expected output.


8. How it is done
Consider the following code example which shows how to make your own class and object to use with a with statement.

Here is the Python code [#4]

Here is the output of the Python code.


9. Custom errors
To cleanly handle file errors, for example, on would create a class to do explicit file operations that has the above routines to more cleanly handle those errors. (Examples left as an exercise).

10. End of page

by RS  admin@robinsnyder.com : 1024 x 640