DevNet Associate DEVASC 200-901 Official Certification Guide by Adrian Iliesiu (z-lib.org)

(andrew) #1

To write these changes back to your file, use the
following code.


Click here to view code image


with open("yaml_sample.yaml", "w") as data:
data.write(yaml.dump(yaml_dict,
default_flow_style=False))

ERROR HANDLING IN PYTHON


Whenever you are working with code, errors are bound
to happen. In Python, errors often halt the execution of
code, and the interpreter spits out some type of cryptic
message. What if you wanted Python to tell the users
what they did wrong and let them try again or perform
some other task to recover from the error? That’s where
the try-except-else-finally code blocks come into play.


You have seen quite a bit of file access in this chapter.
What happens if you ask the user for the filename
instead of hard-coding it? If you did this, you would run
the risk of a typo halting your program. In order to add
some error handling to your code, you can use the try
statement. Example 5-8 shows an example of how this
works.


Example 5-8 try-except-else-finally Code Example

Click here to view code image


x = 0
while True:
try:
filename = input("Which file would you
like to open? :")
with open(filename, "r") as fh:
file_data = fh.read()
except FileNotFoundError:
Free download pdf