Hacking Secret Ciphers with Python

(Ann) #1

158 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


Hello world!








If your text file has multiple lines, the string returned by read() will have \n newline
characters in it at the end of each line. When you try to print a string with newline characters, the
string will print across several lines:





print('Hello\nworld!')
Hello
world!





If you get an error message that says “IOError: [Errno 2] No such file or
directory” then double check that you typed the filename (and if it is an absolute path, the
directory name) correctly. Also make sure that the file actually is where you think it is.


The close() File Object Method
After you have read the file’s contents into a variable, you can tell Python that you are done with
the file by calling the close() method on the file object.





fo.close()





Python will automatically close any open files when the program terminates. But when you want
to re-read the contents of a file, you must close the file object and then call the open() function
on the file again.


Here’s the code in our transposition cipher program that reads the file whose filename is stored in
the inputFilename variable:


transpositionFileCipher.py



  1. Read in the message from the input file



  2. fileObj = open(inputFilename)

  3. content = fileObj.read()

  4. fileObj.close()


Writing To Files


We read the original file and now will write the encrypted (or decrypted) form to a different file.
The file object returned by open() has a write() function, although you can only use this

Free download pdf