Recursive directory traverse and append .png file to list

Python Developer’s Meetup Nepal #13 Question Solution

Q: Write a python script that recursively walks all sub-directories and searches all files with extension *.png or *.PNG and append them to the list.


import os

# list variable to store the .png and .PNG file
png_file_list = []

# Recursive function to traverse all the sub-dirctory and check for png files
def traverse_directory(dir_path):
    for child in os.listdir(dir_path):
        path = os.path.join(dir_path, child)
        if os.path.isdir(path):
        	# split the path and store file name only
        	file_name = path.split('\\')[-1]
        	# split the file name and store extension
        	file_name_extension = file_name.split('.')[-1]
        	# check if the file name has extension .png or .PNG
        	if(file_name_extension == 'png' or file_name_extension == 'PNG'):

# Traverse current directory for files and folders

# Print the final list

Convert the list of images to PDF file and add watermark in Ubuntu

Converting list of images to PDF in Ubuntu
Let’s use ImageMagick tool. Normally it is installed in Ubuntu. If you need to install it then run:

$ sudo apt-get install imagemagick

Then you can convert it by using:
$ convert image_1.jpg image_2.jpg output.pdf

You can specify any numbers of images but the last argument must be a name of your PDF file along with extension (.pdf).

Adding the watermark in the PDF file
We use Python script for adding watermark to each page in the PDF file. We will be using “PyPDF2” python library.

$ pip install PyPDF2

Make your watermark ready, convert it to PDF file. Make sure that watermark file is of same page size as of your PDF file.

Then run this code by modifying the file names:

import PyPDF2

originalFile = open('inputfile_pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(originalFile)
pdfWriter = PyPDF2.PdfFileWriter()

for i in range(0, pdfReader.numPages):
    originalfile_page = pdfReader.getPage(i)
    pdfWatermarkReader = PyPDF2.PdfFileReader(open('watermark.pdf', 'rb'))

resultPdfFile = open('watermarked_outputfile.pdf', 'wb')

Decorators in Python

While learning Python in the beginning, i skipped the portion of the chapters on Decorators. After i worked on Flask and Django, I was introduced with the Decorators.

Let us consider a simple flask app example:

def hello():
    return "Hello World!"

In this code the line with @ symbol is decorators. Decorators is one of the important feature in Python that you must learn to master it. It is not that hard, so let us learn it.

First let us see Closures

>>> def out_func():
...     def in_func():
...             print("I am inner function")
...     return in_func
>>> call = out_func()
>>> call
<function in_func at 0x7f0d6819a758>
>>> call()
I am inner function

Also let us see by passing the parameter in the function.

>>> def out_func():
...     def in_func(x):
...             print(x)
...     return in_func
>>> call = out_func()
>>> call
<function in_func at 0x7f66ff93f5f0>
>>> call(3)

We can also pass the function as the parameter in the function. Let us write a function wrap which takes a function. We write another function checkNumber inside the wrap. It’s main task is to return same number if the number is greater than or equal to 100 otherwise return number by adding 100. It actually adds 100 using function that we pass to wrap.

We also write function incrementHundered to add 100 to passed number.

def wrap(func):
   def checkNumber(a): # check
       return (a if a >= 100 else func(a))
   return checkNumber

def incrementHundered(a):
    return a+100

# We pass incrementHundered to wrap
incrementHundered = wrap (incrementHundered) # decorators

print (incrementHundered(2)) # 102
print (incrementHundered(300)) # 300
print (incrementHundered(29)) # 129

The above code can be re-written using @ symbol for decorators as follows:

def wrap(func):
   def checkNumber(a): # check
       return (a if a >= 100 else func(a))
   return checkNumber

def incrementHundered(a):
    return a+100

print (incrementHundered(2)) # 102
print (incrementHundered(300)) # 300
print (incrementHundered(29)) # 129

By writing @wrap and function just below it, think as if we have passed whole function to wrap. And it works as usual. So that was the quick and easy introduction to Decorators.

I hope you understood the Decorators.

Django Tutorial – Building URL Shortener with Django

I finally got the time to write a Django tutorial. In this tutorial we are building URL Shortener. If you are confused with what we are building then we are building something similar to ( or (

We are building the app that will make a shorter URL of a longer URL. (Example) Normally the shorter URL will be localhost:8000/4hh5kr for

I am using Django 1.7.1 with Python 3.3.2+. Don’t worry if you have different version of Django because we will set up our virtual environment and install latest version of Django. But be sure you do have Python 3+ because installing Python will not be covered in this tutorial.

I assume that you have completed Writing your first Django app. It is not really essential to complete this tutorial but it is highly recommended that you complete this tutorial before we begin. It will give you a lot of knowledge that will be useful in this tutorial.

You can also get the source code of this app in Github(django_urlshortener).

This tutorial is divided into 5 parts:

Continue reading “Django Tutorial – Building URL Shortener with Django”

Setup Google App Engine Python SDK in Ubuntu

First of all download Google App Engine SDK for Linux.

Extract it anywhere within your local folder. It can be anywhere such as in your home directory or Documents directory.

Open terminal (ctrl+alt+t) and navigate to your home directory and open .bashrc to edit with this command:

$ sudo gedit .bashrc

At the end of the file, add these lines by changing the directory to your google_appengine folder. The first line is just a comment and in the second line /usr/local/google_appengine is the path to the google_appengine folder.

### Added for GAE
export PATH="/usr/local/google_appengine:$PATH"

Now restart your computer and then you should be able to use $ command from anywhere.