Hacking Secret Ciphers with Python

(Ann) #1
Chapter 11 – Encrypting and Decrypting Files 159

function if you open the file in “write” mode instead of “read” mode. You do this by passing the
string value 'w' as the second parameter. For example:





fo = open('filename.txt', 'w')





Along with “read” and “write”, there is also an “append” mode. The “append” is like “write”
mode, except any strings written to the file will be appended to the end of any content that is
already in the file. “Append” mode will not overwrite the file if it already exists. To open a file in
append mode, pass the string 'a' as the second argument to open().


(Just in case you were curious, you could pass the string 'r' to open() to open the file in read
mode. But since passing no second argument at all also opens the file in read mode, there’s no
reason to pass 'r'.)


The write() File Object Method


You can write text to a file by calling the file object’s write() method. The file object must
have been opened in write mode, otherwise, you will get a “io.UnsupportedOperation:
not readable” error message. (And if you try to call read() on a file object that was
opened in write mode, you will get a “io.UnsupportedOperation: not readable”
error message.)


The write() method takes one argument: a string of text that is to be written to the file. Lines
43 to 45 open a file in write mode, write to the file, and then close the file object.


transpositionFileCipher.py



  1. Write out the translated message to the output file.



  2. outputFileObj = open(outputFilename, 'w')

  3. outputFileObj.write(translated)

  4. outputFileObj.close()


Now that we have the basics of reading and writing files, let’s look at the source code to the
transposition file cipher program.


How the Program Works..........................................................................................................................................


transpositionFileCipher.py



  1. Transposition Cipher Encrypt/Decrypt File




  2. http://inventwithpython.com/hacking (BSD Licensed)





  3. import time, os, sys, transpositionEncrypt, transpositionDecrypt



Free download pdf