Sunday, 3 December 2017

Decoding Secret Message with Python

Planning a Secret Message

Renaming a folder of 50 files will allow a puzzle to be solved.

The scenario involves a scrambled message because of the naming convention of image files. These files begin with numbers. If the numbers are removed, the images will be renamed and alphabetically categorized. Thereby revealing a message in the photos.

I will need to do the following:
  1. Gather file names from the folder
  2. Then rename or remove the numbers from each of the files within the folder

Here is the code and the explanation to do step 1 which is to gather file names from the folder:
import os #imports module, os
def rename_files(): #defines a new function
    file_list = os.listdir(r"C:\Users\HG Wells\Google Drive\Tech\Udacity\prank") #defines variable file_list and assigns functions listdir from the os module. This is added to import the list given the path file. R is to take string as is and not interpret it differently.
    print(file_list) #instruction to print variable file_list
rename_files() #runs defined function rename_files

The following will be the output when this function is run:

Step 2 is to rename the files. I will use the rename function from module os to accomplish this:

import os
def rename_files():
    #(1) retrieve files given folder location
    file_list = os.listdir(r"C:\Users\HG Wells\Google Drive\Tech\Udacity\prank")
    print(file_list)
    #shows current directory, which is where rename_files.py is saved.
    saved_path = os.getcwd()
    print("Current Working Directory is "+saved_path)
    #Changed current directory to the folder with the files we want to rename
    os.chdir(r"C:\Users\HG Wells\Google Drive\Tech\Udacity\prank")
    #(2) rename each file
    #loop to change each file in list
    for file_name in file_list:
    #runs rename function from os module where file_name is current name, and file_name.translate is function to rename what file should be named  
    #syntax for file_name.translate on the second line will remove the numbers found in files
        os.rename(file_name, file_name.translate(None,"0123456789"))
    #moves current directory back to original place
    os.chdir(saved_path)
rename_files()

Upon looking at the images in the folder, I can see that the images have new names (no longer has numbers) and the secret code is displayed:
(Photos from Udacity)
Keys are in the closet behind the shoe box.