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 complete files.
Reading and writing to files can be quite dependent on factors that are outside of the direct control of the script, such as whether the file that we are trying to open exists or the filesystem has space to store a new file. Therefore, 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 similar to 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...