Book Image

Raspberry Pi cookbook for Python programmers

Book Image

Raspberry Pi cookbook for Python programmers

Overview of this book

Table of Contents (18 chapters)
Raspberry Pi Cookbook for Python Programmers
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using files and handling errors


In addition to easy string handling, Python allows you to read, edit, and create files easily. So, by building upon the previous scripts, we can make use of our encryptText() function to encode whole files.

Since reading and writing to files can be quite dependent on factors that are outside of the direct control of the script, such as if the file we are trying to open exists or if the filesystem has space to store a new file, we will also take a look at how to handle exceptions and protect operations that may result in errors.

Getting ready

The following script will allow you to specify a file through the command line, which will be read and encoded to produce an output file. Create a small text file named infile.txt and save it so that we can test the script. It should include a short message like the following:

This is a short message to test our file encryption program.

How to do it…

Create the fileencrypt.py script using the following code:

#!/usr/bin/python3...