Day 27: Renaming Image Files And Photos Bulkwise With Python


One of my most dreaded tasks on the computer is the renaming of images. When I import them from the digicam they’re usually just numbered.


I like to name my photos with a concrete name. For example “rome_2015” or “linus” when I have taken images of my dog. The images also get a numbered index 01,02,03,aso.


Well it’s dreaded not anymore because I wrote a little Python script that will do all the tedious work for me in an instance.


Not only do we rename the images, the program will also detect other files (like system files) and leave them untouched.


Here is a before and after:



To do this the python script needs to know the directory where the photos are located, the desired filename and what file type we like to change (.jpg)


Here is the code (the comments explain the function line by line)


import os

directory = "img/"                              # get the image-directory
absolute_dir = os.getcwd()                      # get your current working dir
complete_dir = absolute_dir + "/" + directory   # built a complete path to the images

#if you would need the desktop dir on mac - use the line below
#complete_dir = os.path.expanduser("~/Desktop/test/")

num_of_files = 0                                # set counter for image-numbers
name = "linus"                                # what you want to name you images

# go through every file in given dir
for filename in os.listdir(complete_dir):
    if filename.endswith(".jpg"):               # only operate on .jpg files, can be changed to any filetype
        num_of_files += 1                       # thats the number we indes our fotos with

        new_name = name + "_" + str(num_of_files) + ".jpg" # build the new file name

        # rename the file, we need complete_dir here because
        # listdir and rename work on different (absolute and increment) directorys
        # otherwise we will get an error
        os.rename(complete_dir + filename, complete_dir + new_name)

Day 26: Elegant And Lean Python


Just something quick today I stumbled upon yesterday:


# checking if the variable name has a value
# using the most efficient way

name = input("Enter your name: ")

# this works, but dont do this
if (len(name) > 0):

# this works also, but it's also bad style
if (name != ""):

# This is the proper Python way
# if name has a value it checks out true automatically
if (name):

Day 23: Dir, Help And Pdb – Make Use Of Pythons Little Helpers


The shell command dir lists all attributes an object has – and remember everything in Python is an object.

Start your terminal and enter “python” to start the IDLE mode. Then type for example dir(‘linus’) and you will

get all the attributes for “linus” which in this case is a string.



Pretty neat isn’t it? But that’s not all Python will do for you. The help-function will deliver even deeper information

about other functions. We can use it on the command ‘linus’.lower for example like this:




Here is the output:



The help-function returns information about virtually everything in Python.


Your Python comes with its own Docs installed – amazing!


And there is even more you say? Yes indeed! With pdb Python has its own integrated debugger!


With the debugger you can go through your code line by line and look up any possible bugs!


To use pdb you will have to include the following lines in the code.


import pdb



Once you run the program the execution will stop once the interpreter comes across the pdb.set_trace() command.

You will be redirected to the shell where you can go through every line manually and see how your

code behaves. With “n” or “next” you can jump to the next line of code.


pdb can do a lot more for you actually. You find the complete documentation here




Day 21: A String Of Events – Some Basic String Consideration


Just some basic string paradigms. Explanation in comments


name =  "Robert"
age = 42

print("{} is {}".format(name, age))   # Output: Robert is 42

print("Name: {:*^22}".format("Ringo"))  # Output: ********Ringo*********

(5).conjugate()         # 5 needs to be in parantheses. Otherwise Python confuses the . with a float

filename = ""

# fyi: we use lower() to catch unformated user input
print(filename.lower().endswith(".java"))     # returns False
print(filename.lower().endswith(".py"))       # returns True

print(filename.lower().startswith("world"))   # return False
print(filename.lower().startswith("hello"))   # return True

print(filename.find("py"))                    # returns 6 - the index of "p"

print(filename.find("java"))                  # returns -1

Day 20: A Very Simple Music Player In Python


We use pyglet to play an mp3-file – this is a very simple example.

The player has no controls – I just wanted to make a point and play a Music-File from the Shell

We need AVBin installed on the computer to decode the MP3-File


#! A very simple Music player
# Pyglet handles the playing of the audio files
# we need AVBin to decode the mp3 file 
# otherwise we get an error

import pyglet           

music ='music.mp3')  # get the media file

Day 19: Count the Raven how many words?

This little script delivers the number of words in a text-file.

Our example uses the poem “The Raven” by Edgar Allen Poe

but the program works for any .txt-File.


#! Count words in a .txt file
# open a given txt-file and read it line by line
# split the words from the string with line.split()

import os
num_words = 0

with open("the_raven.txt", 'r') as f:
    for line in f:
        words = line.split()
        num_words += len(words)

print("Number of words:")           # Output: Number of words:
print(num_words)                    # Output: 1067

Day 13/14: Cracking the Code – the string maketrans function


In this episode we are cracking one challenge from the amazon Python Challenge


In entry two there is a encrypted code that needs some cracking!

If you look closely at the string you notice that all letters are shifted by two. Instead of “abc” its “cde” and so on.

To crack this code we use the maketrans-function.


Here is the code:

import string

raw = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle grgl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."

# the maketrans function transforms our coded string with a new set of letters
table = string.maketrans(
    "abcdefghijklmnopqrstuvwxyz", "cdefghijklmnopqrstuvwxyzab"

# setting up the decoded string for printing.
result = raw.translate(table)


The output looks like this:


Day 12: Do It Like The Greeks – Basic Arithmetic Operations In Python


Today just some samples of basic operation and their output on the shell.


print(type(1))      # class "int"
print(type(2.45))   # class "float"

print(2 + 3.5)      # 5.5 <-- int gets converted to float auto

number = 5
number += 4         # 9 <-- number =  number + 4


print(.4+.01)       # 0.4100000000003 <-- float will have some rounding error

print(2 - 3.5)      # -1.5

print(6 * 2)        # 12
print(6 * .25)      # 1.5
print(4.5 * 2.3)    # 10.35

print(12 / 4)       # 3
print(3 / 4)        # 0.75 <-- output is a float
print(3 // 6)       # 0 integer division

print(4 % 3)        # 1
print(3 % 2)        # 1 <-- odd number
print(6 % 3)        # 0 <-- even number

print(4 ** 2)       # 16
print(4 ** 6)       # 4096

print(3 + 6 * 2)    # 15 <-- * and / before + and -
print((3 + 6) * 2)  # 18 <-- paranthesises come before * and /
print(((3 / 2) + 6 * .5) * 2)   # 9.0

Day 10/11: 99 In The Shade – we’re building a Fahrenheit-Converter with Python

Its a simple function that converts Celsius to Fahrenheit.



We only have exception and thats when the user enters a number below absolute zero (-273.15 degree celsius).


def fahrenheit(celsius):
    convToFahrenheit = 9.0/5.0 * celsius + 32
    return convToFahrenheit

celsius = (float(input("Enter Celsius: ")))

if celsius >= -273.15:
    print ("Fahrenheit: " + str(fahrenheit(celsius)))
    print ("Sorry the lowest possible temperature in Celsius is -273.15 degrees.")

Day 9: Pythons Safe Words – dont use Keywords and Built-ins!

Python has a number of Keywords that you are not allowed to use as class, function or variable names.





























Python has also a variety of build-in-functions like print() and object(). While you are not allowed to use keywords
in any other context, you can name a variable or a function “print” or “object” without getting an error. But you really
shouldn’t do this since your own object will override or shadow the build-in-function – at least name wise.

If you write a function “def print(x):” it will work just fine as long as you don’t want to use the buld-in print-method.

So it is really not recommended to use any of these build-ins