Hacking Secret Ciphers with Python

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

Sample Run of the Transposition File Cipher Program


When you run the above program, it produces this output:


Encrypting...
Encryption time: 1.21 seconds
Done encrypting frankenstein.txt (441034 characters).
Encrypted file is frankenstein.encrypted.txt.


A new frankenstein.encrypted.txt file will have been created in the same directory as
transpositionFileCipher.py. If you open this file with IDLE’s file editor, you will see the
encrypted contents of frankenstein.py. You can now email this encrypted file to someone for them
to decrypt.


Reading From Files


Up until now, any input we want to give our programs would have to be typed in by the user.
Python programs can open and read files directly off of the hard drive. There are three steps to
reading the contents of a file: opening the file, reading into a variable, and then closing the file.


The open() Function and File Objects


The open() function’s first parameter is a string for the name of the file to open. If the file is in
the same directory as the Python program then you can just type in the name, such as
'thetimemachine.txt'. You can always specify the absolute path of the file, which
includes the directory that it is in. For example, 'c:\Python32\frankenstein.txt'
(on Windows) and '/usr/foobar/frankenstein.txt' (on OS X and Linux) are
absolute filenames. (Remember that the \ backslash must be escaped with another backslash
before it.)


The open() function returns a value of the “file object” data type. This value has several
methods for reading from, writing to, and closing the file.


The read() File Object Method


The read() method will return a string containing all the text in the file. For example, say the
file spam.txt contained the text “Hello world!”. (You can create this file yourself using IDLE’s
file editor. Just save the file with a .txt extension.) Run the following from the interactive shell
(this codes assumes you are running Windows and the spam.txt file is in the c:\ directory):





fo = open('c:\spam.txt', 'r')
content = fo.read()
print(content)




Free download pdf