Search This Blog

Monday, September 28, 2015

Directory Navigation in python - Script

import os,re,shutil,fnmatch

ex_path="D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\Glob"

# Clean up
if not os.path.exists(ex_path):
    os.mkdir(ex_path)
else:
    shutil.rmtree(ex_path)
    os.mkdir(ex_path)

os.chdir(ex_path)

# Pre-Requisites
dir_list=[]

for i in range(0,4):
    dir_name="dir_%d" %i
    os.mkdir(dir_name)
    dir_list.append([dir_name])

for directory in dir_list:
    print directory[0]
    dir_path=ex_path+"\\" + directory[0]
    print dir_path
    os.chdir(dir_path)
    for i in range(0,4):
        fdesc=open("file_%s_%s" %(directory[0],i),"w")
        fdesc.close()
 
os.mkdir("sub_directory")
change_path=ex_path+"\dir_3\sub_directory"
print change_path
os.chdir(change_path)
fdesc=open("subdirectory.txt","w")
fdesc.close()

for dirpath, dirs, files in os.walk(ex_path):
    path = dirpath.split("\\")
    print len(path)
    print '|',(len(path))*'---','[',os.path.basename(dirpath),']'
    for f in files:
        print "|",(len(path))*'---',f

     
OUTPUT: ======= >>> ================================ RESTART ================================ >>> dir_0 D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\Glob\dir_0 dir_1 D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\Glob\dir_1 dir_2 D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\Glob\dir_2 dir_3 D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\Glob\dir_3 D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\Glob\dir_3\sub_directory 6 | ------------------ [ Glob ] 7 | --------------------- [ dir_0 ] | --------------------- file_dir_0_0 | --------------------- file_dir_0_1 | --------------------- file_dir_0_2 | --------------------- file_dir_0_3 7 | --------------------- [ dir_1 ] | --------------------- file_dir_1_0 | --------------------- file_dir_1_1 | --------------------- file_dir_1_2 | --------------------- file_dir_1_3 7 | --------------------- [ dir_2 ] | --------------------- file_dir_2_0 | --------------------- file_dir_2_1 | --------------------- file_dir_2_2 | --------------------- file_dir_2_3 7 | --------------------- [ dir_3 ] | --------------------- file_dir_3_0 | --------------------- file_dir_3_1 | --------------------- file_dir_3_2 | --------------------- file_dir_3_3 8 | ------------------------ [ sub_directory ] | ------------------------ subdirectory.txt >>> >>> os.stat("D:\Deepti\SPSE-Course-DVD\Exercises\sample.xml" ) nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=219334L, st_atime=1441614421L, st_mtime=1441614386L, st_ctime=1441614421L) >>> os.lstat("D:\Deepti\SPSE-Course-DVD\Exercises\sample.xml") nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=219334L, st_atime=1441614421L, st_mtime=1441614386L, st_ctime=1441614421L)


Directory Navigation in Python - Command line

import os
import glob
import shutil
import fnmatch
import re


ex_path="D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\Glob"
#Cleanup
print "Cleaning up"
if os.path.exists("D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\NewDirectory"):
    os.rmdir("D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\NewDirectory")

if os.path.exists(ex_path):
    # Remove directory and all its contents
    shutil.rmtree(ex_path)

print "Display the current directory path"
print "   %s" %os.getcwd()

print "Create a new directory"
os.mkdir("D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\NewDirectory")

print "List contents of directory"
print os.listdir("D:\Deepti\SPSE-Course-DVD\Exercises\Module 2")

for item in os.listdir("D:\Deepti\SPSE-Course-DVD\Exercises\Module 2"):
    if os.path.isfile(item):
        print "  %s is a file" %item
    elif os.path.isdir(item):
        print "  %s is a directory" %item
    else:
        print "  %s: Unknown filetype" %item
     
print "Remove directory"
os.rmdir("D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\NewDirectory")

print "List contents of directory"
print os.listdir("D:\Deepti\SPSE-Course-DVD\Exercises\Module 2")



# Pre-requisites

os.mkdir("D:\Deepti\SPSE-Course-DVD\Exercises\Module 2\Glob")


file1=open(os.path.join(ex_path,"pythonfile.py"),"w")
file1.close()

file2=open(os.path.join(ex_path,"textfile.txt"),"w")
file2.close()

file3=open(os.path.join(ex_path,"swapfile.swp"),"w")
file3.close()

print "List contents of directory"
print os.listdir(ex_path)


# Exercise on glob
print "---- Print all the python files ----"
print glob.glob(os.path.join(ex_path,"*.py"))

# Exercise on fnmatch
print "---- Match file pattern using fnmatch ----"
print fnmatch.fnmatch(os.path.join(ex_path,"swapfile.swp"),"*.swp")
print fnmatch.fnmatchcase(os.path.join(ex_path,"SWAPFILE.swp"),"*.swp")
print fnmatch.fnmatchcase(os.path.join(ex_path,"waspfile.swp"),"*.swp")

# Prints False
print fnmatch.fnmatchcase(os.path.join(ex_path,"swapfile.SWP"),"*.swp")

fnmatch_pattern=fnmatch.translate("*.swp")
print fnmatch_pattern

reobj=re.compile(fnmatch_pattern)
print reobj

print reobj.match('swap.swp')

# Print set of files from a list of files
Files=['__init__.py', 'fnmatch_filter.py', 'fnmatch_fnmatch.py', 'fnmatch_fnmatchcase.py', 'fnmatch_translate.py', 'index.rst']
print 'Matches:', fnmatch.filter(Files,"*.py")







 

Thursday, March 5, 2015

Data Types: Tuples, Sets, Dictionaries

Tuples:


Tuples are similar to lists but they are immutable. We can convert as list to tuple ans vice versa.

>>> mytuple=tuple(["Harry Potter",25,100,3])
>>> mytuple

('Harry Potter', 25, 100, 3)

Note that tuple has () instead of a list's []

>>> moviename,runningTime,upVotes,downVotes=mytuple
>>> moviename
'Harry Potter'
>>> runningTime
25
>>> upVotes
100
>>> downVotes

3


Sets:

Sets are unordered collection of unique objects.

List to a set: myset = set(moviename)
Set to list: mylist = list(myset)

>>> a=set([1,2,3,3,2])
>>> a

set([1, 2, 3])

Sets have only unique items

>>> b=set([3,4,5])
>>> b
set([3, 4, 5])
>>> a|b

set([1, 2, 3, 4, 5])

Intersection of sets

>>> a&b
set([3])

>>> 


>>> a-b

set([1, 2])
>>> b-a
set([4, 5])

>>> 

Sets are useful in finding different unique values


Dictionaries:


Dictionaries are unordered key-value pairs

a={}
Empty dictionary

>>> a={"Movie":"Harry Potter", "sitCom":"Big bang theory"}
>>> print a
{'Movie': 'Harry Potter', 'sitCom': 'Big bang theory'}










Variables and Data Types


             Reference
Name ----------------> Deepti
Variable                     Object


  • "Name", which is a variable acts as a reference to "Deepti" which is an object
  • It is the object that has the data type associated with it,


>>> id(name)
42209536
>>> hex(id(name))
'0x2841100'
>>> name.__repr__
<method-wrapper '__repr__' of str object at 0x02841100>
>>> 


>>> name = "Deepti"
>>> name = 'deepti'
>>> name = "Deepti\nvaidyula"
>>> name
'Deepti\nvaidyula'



  • # The 'r' here tells that it is a raw string and don't interpret the \n

>>> name = r"Deepti\nvaidyula" 
>>> name
'Deepti\\nvaidyula'

>>> print name
Deepti\nvaidyula
>>> name = "Deepti\nvaidyula"
>>> print name
Deepti
vaidyula


  • # Python also supports unicode

>>> name = u"Deepti"
>>> name

u'Deepti'

# Convert unicode to String - use str
>>> str(name)
'Deepti'
>>> name
u'Deepti'


  • Use 'unicode' to convert to unicode




  • We cannot directly change string objects in memory as they are immutable

>>> name = "Daniel"
>>> name[0]
'D'
>>> name[0] = 'a'

Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    name[0] = 'a'

TypeError: 'str' object does not support item assignment
>>> name = "Radcliffe"
>>> name

'Radcliffe'


>>> a="Daniel"
>>> name = a
>>> name
'Daniel'
>>> a

'Daniel'



>>> a="Radcliffe"
>>> a
'Radcliffe'
>>> name
'Daniel'

String Concatenation

fn = "deepti"
ln = "Vaidyula"

full_name = fn + ln
print full_name
full_name = fn + ' ' + ln
print full_name

>>> 
deeptiVaidyula
deepti Vaidyula

  • Python like most high languages has garbage collection. When any object is no longer referenced by any variable, it is automatically cleaned up.
  • Repeated sequence in string
>>> rhyme = "twinkle"
>>> print rhyme*2 + " little star"
twinkletwinkle little star

String Slicing


  • string[start:end:steps]


>>> num="123456789"
>>> print num[5]
6
>>> print num[5:8]
678
>>> print num[5:8:2]
68
>>> print num[5:8:2]
KeyboardInterrupt
>>> print num[5:8:1]
678
>>> print num[5:9:1]
6789
>>> print num[5:9:2]
68
>>>


  • num.find returns the index

>>> num.find("5")
4

>>> num.find("abc")
-1
>>>
"abc" is not present in num

>>> name = "Daniel Radcliffe"
>>> name.split()
['Daniel', 'Radcliffe']
>>> 

>>> name = "Daniel:Radcliffe"
>>> name.split(":")
['Daniel', 'Radcliffe']

>>> name.replace("Daniel", "Ginny")

'Ginny:Radcliffe'

String Formatting

>>> ip="192.168.12.38"
>>> print "Hack this ip : %s" %ip
Hack this ip : 192.168.12.38

Operations and Lists



>>> 2 + 2
4
>>> list=[1,2,3,4]
>>> list[0]
1
>>> list[-1]
4
>>> len(list)

4


  • Lists are heterogenous. So, we can mix numbers and alphabet


>>> mylist=[1,2,3,4,["a","b","c"]]
>>> mylist
[1, 2, 3, 4, ['a', 'b', 'c']]
>>> len(mylist)

5
>>> mylist.append(5)
>>> mylist
[1, 2, 3, 4, ['a', 'b', 'c'], 5]
>>> mylist.reverse()
>>> print mylist.reverse()
None
>>> mylist.pop()
5
>>> mylist
[1, 2, 3, 4, ['a', 'b', 'c']]
>>> mylist.insert(4,"inserted")
>>> mylist

[1, 2, 3, 4, 'inserted', ['a', 'b', 'c']]
>>> mylist

[1, 2, 4, 'inserted', ['a', 'b', 'c']]













Tuesday, May 27, 2014

Faster commands that improve performance


  • Tuple is faster than list
  • An operation like a_list = a_list + 1 is memory intensive

Saturday, May 3, 2014

Python - Cat animation using Pygame

import pygame, sys
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((400,300))
FPS = 30
fpsClock = pygame.time.Clock()

pygame.display.set_caption('Animation')

BLACK = (0,0,0)
WHITE = (255,255,255)
RED   = (255,0,0)
BLUE  = ( 0, 0, 255)

catImg = pygame.image.load('cat.jpg')
catx = 10
caty = 10
direction = 'right'
                           

while True:
    screen.fill(WHITE)
    if direction == 'right':
        catx += 5
        if catx == 360 :
            direction = 'down'
    elif direction == 'down':
        caty += 5
        if caty == 260:
            direction ='left'
    elif direction == 'left':
        catx -= 5
        if catx == 10:
            direction = 'up'
    elif direction == 'up':
        caty -= 5
        if caty == 10:
             direction = 'right'
    screen.blit(catImg, (catx,caty))
    
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()
    fpsClock.tick(FPS)



Tuesday, March 25, 2014

Print a hollow diamond - with numbers


if __name__ == "__main__" :
    try:
        act_size = int(input("Enter the size of the diamond : "))
        size=1
        size_max = 2*act_size - 1
        level=1
        i_size = 2 * act_size
        for j in range(0,i_size):
            pos=1         
            for i in range(i_size):
                if pos > act_size - level+1 and pos <=act_size+level-1 and level<=act_size :
                    print(" ", end='')
                elif pos <= act_size and size < 2*act_size and level<=act_size :
                    print(size, end='')
                    size += 2
                elif pos > act_size and pos <= i_size and level<=act_size :
                    size -= 2
                    print(size, end='')
                if level > act_size and pos <= level - act_size:                 
                    print(size_max,end='')
                    size_max += 2                   
                elif level > act_size and pos > i_size - level + act_size :
                    size_max -= 2
                    print(size_max,end='')                   
                elif level > act_size:
                    print(" ",end='')
               
                pos += 1
            size_max = 2*(i_size-level)-1
            size = (2*level) + 1
            level += 1
            print("")
               
    except :
        print("ERROR: Only numbers are accepted")