Hacking Secret Ciphers with Python

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

(Of course, you will only get the above results if you are running Python on Windows. The
calc.exe file does not exist on OS X or Linux.)


transpositionFileCipher.py



  1. If the input file does not exist, then the program terminates early.



  2. if not os.path.exists(inputFilename):

  3. print('The file %s does not exist. Quitting...' % (inputFilename))

  4. sys.exit()


We use the os.path.exists() function to check that the filename in inputFilename
actually exists. Otherwise, we have no file to encrypt or decrypt. In that case, we display a
message to the user and then quit the program.


The startswith() and endswith() String Methods


transpositionFileCipher.py



  1. If the output file already exists, give the user a chance to quit.



  2. if os.path.exists(outputFilename):

  3. print('This will overwrite the file %s. (C)ontinue or (Q)uit?' %
    (outputFilename))

  4. response = input('> ')

  5. if not response.lower().startswith('c'):

  6. sys.exit()


If the file the program will write to already exists, the user is asked to type in “C” if they want to
continue running the program or “Q” to quit the program.


The string in the response variable will have lower() called on it, and the returned string from
lower() will have the string method startswith() called on it. The startswith()
method will return True if its string argument can be found at the beginning of the string. Try
typing the following into the interactive shell:





'hello'.startswith('h')
True
'hello world!'.startswith('hello wo')
True
'hello'.startswith('H')
False
spam = 'Albert'
spam.startswith('Al')
True




Free download pdf