
Python code snippets:
Python is a very powerfull scripting language. Following is a few code snippets on how do to common things that is easy to forget. So you can just copy paste them into your code if you ever need it.-> Formating time and date
-> Simple use of regular expressions
-> Use of range in for loops
-> How to check if a file exists
-> Simple use of regular expressions
-> Simple use of lists
-> Random file name or string
-> Add digits to a file name
-> Common string methods
-> Notes on slicing.
Formating time and date:
001: #!/usr/bin/python
002:
003:
004: import time #Imports the time module.
005:
006: gmt = time.gmtime(time.time()) #The actual time and date.
007: fmt = `(%a. %d %b %Y %H:%M:%S GMT+1)` #The format we want it in.
008:
009: time_string = time.strftime(fmt, gmt) #Formats the actual time and date.
010:
011: print time_string #Prints: (Tue. 10 Jan 2006 16:49:48 GMT+1).
012:
013: #More on time and date: http://docs.python.org/lib/module-time.html
Simple use of regular expressions:
001: #!/usr/bin/python
002:
003: import re #import the regex module.
004:
005: p = re.compile(`bbaa`, re.IGNORECASE) #Make up the regular expression.
006: m = p.search("abbbaaaab") #Search a string.
007:
008: if m:
009: print "String found at index: " + str(m.start()) #print out where we found it.
010:
011:
012: #More on regex: http://www.python.org/doc/2.3.5/lib/module-re.html
Use of range in for loops:
001: #!/usr/bin/python
002:
003: minutes = 3 #The number of times we want the for loop to run.
004:
005: print "Minutes left: " ,
006:
007: for i in range(minutes): #Setting up the for loop with range.
008: print str(minutes - i) + ", " , #Printing out something.
009:
010: print "0."
011:
012:
013: #Output:
014: #Minutes left: 3, 2, 1, 0.
How to check if a file exists:
001: #!/usr/bin/python
002:
003: import os #import the os module.
004:
005: if os.path.isfile(`somefile.txt`): #Check if file exists.
006: print `file exists!` #print yes, if it does.
007: else:
008: print "file does NOT exists" #print no, if it doesn`t.
Simple use of regular expressions::
001: #!/usr/bin/python
002:
003: import os
004:
005: st = os.stat(`somefile.txt`) #Find filesize, method 1.
006: size1 = str(st[6])
007:
008: size2 = str(os.path.getsize(`somefile.txt`)) #Find filesize, method 2.
009:
010: print "file size is: " + size1
011: print "file size is really: " + size2
012:
013:
014: #Output:
015: #file size is: 336
016: #file size is really: 336
Simple use of lists:
001: #!/usr/bin/python
002:
003: start_list = [] #Make list 1.
004: start_list2 = [] #Make list 2.
005:
006: start_list.append("1") #Add values to list 1.
007: start_list.append("2")
008: start_list.append("3")
009: start_list.append("4")
010: start_list.append("5")
011: start_list.append("6")
012:
013:
014: start_list2.append("hello") #Add values to list 2.
015: start_list2.append("hello")
016:
017: print "First list: " + str(start_list) #print the first list.
018:
019: start_list = start_list2 #Set list one to point at list 2.
020: start_list2.append("again") #Add one more value to list 2.
021:
022: print "First list now: " + str(start_list) #First list are now pointing at the
023: #same list as list 2.
024:
025:
026: #Output:
027: #First list: [`1`, `2`, `3`, `4`, `5`, `6`]
028: #First list now: [`hello`, `hello`, `again`]
Random file name or string:
001: #!/usr/bin/python
002:
003: import random
004:
005: #Generates a ranomd 15 letter string, that can be used as a tmp file name.
006: def random_string():
007: """Generates a radom 15 letter string that can be used as file names"""
008:
009: letters = [`a`,`b`,`c`,`d`,`e`,`f`,`g`,`h`,`i`,`j`,`k`,`l`,`m`]
010: letters += [`n`,`o`,`p`,`q`,`r`,`s`,`t`,`u`,`v`,`w`,`x`,`y`,`z`]
011: letters += [`A`,`B`,`C`,`D`,`E`,`F`,`G`,`H`,`I`,`J`,`K`,`L`,`M`]
012: letters += [`N`,`O`,`P`,`Q`,`R`,`S`,`T`,`U`,`V`,`W`,`X`,`Y`]
013: letters += [`1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `0`]
014:
015: random_str = ``
016:
017: # Add one and one random letter or digit.
018: for i in range(0, 14):
019: random_str += letters[random.randrange(0, len(letters) - 1)]
020:
021:
022: return random_str
Add digits to a file name:
001: #!/usr/bin/python
002:
003: import os
004:
005: # Takes a filename, and find a number to add to the end of it, that is not already used.
006: def add_number_to_filename(filename):
007:
008: file_exists = True
009: number = 1
010:
011:
012:
013: if os.path.isfile(filename): #Check if file exists.
014: #Start adding numbers to it, if it already exists.
015:
016: while file_exists:
017: if os.path.isfile(filename[:-2] + "-" + str(number)): #Check if file exists.
018: number += 1 #file did exists.
019: else:
020: file_exists = False #This file does not exists.
021:
022: return filename[:-2] + "-" + str(number)
023:
024:
025: # if the file name is not used, then just return it as it is.
026: return filename
027:
028:
Common string methods:
001: #!/usr/bin/python
002:
003:
004: my_string = `Hello World`
005:
006: # Count method:
007: print "There is " + str(my_string.count(`o`)) + " occurrences of the letter o in this string."
008:
009: # Find method:
010: print "Letter o can be found at index " + str(my_string.find(`o`)) + " when searching from the left."
011: print "Letter x can be found at index " + str(my_string.find(`x`)) + " (meaning not found)."
012:
013: # RFind method:
014: print "Letter o can be found at index " + str(my_string.rfind(`o`)) + " when searching from the right."
015:
016: # Join method:
017: print "We can add a string between ever letter like this: " + " ".join(my_string) + "."
018:
019: # Replace method:
020: print "We can replace a char for every occurrence like this: " + my_string.replace(`o`, `x`) + "."
021: print "Or we can simply change a whole word or more like this: " + my_string.replace(`World`, `Mum`)
022:
023: # Split method:
024: print "We can split up a string into a list likt this: " + str(my_string.split(` `))
025:
026: # Strip method:
027: print "We can strip the start and end of a string like this: " + `Hello World`.strip(`Hled`)
028:
029: # Multiply char:
030: print "We can add repetative chars like this: " + "0" * 6 + "."
031:
032: #Output:
033: #There is 2 occurrences of the letter o in this string.
034: #Letter o can be found at index 4 when searching from the left.
035: #Letter x can be found at index -1 (meaning not found).
036: #Letter o can be found at index 7 when searching from the right.
037: #We can add a string between ever letter like this: H e l l o W o r l d.
038: #We can replace a char for every occurrence like this: Hellx Wxrld.
039: #Or we can simply change a whole word or more like this: Hello Mum
040: #We can split up a string into a list likt this: [`Hello`, `World`]
041: #We can strip the start and end of a string like this: o Wor
042:
Notes on slicing:
001: #!/usr/bin/python
002:
003:
004: my_string = `Hello World`
005:
006:
007: # Slicing: #Returns:
008: print my_string[:] #Hello World (Whole string)
009: print my_string[0:] #Hello World (Whole string)
010: print my_string[1:] #ello World (Start from index one and onward)
011: print my_string[0:1] #H (Only index 0)
012: print my_string[0] #H (Only index 0)
013: print my_string[6:] #World (Index 6 and onward)
014:
015: print my_string[:-1] #Hello Worl (Take away the last letter)
016: print my_string[-1] #d (Only print the last letter)
017: print my_string[6:-1] #Worl (From index 6, but take away last letter)
018: print my_string[-5:-1] #Worl (Index -5 equals 6 in this example)
019: print my_string[-5:] #World (From index -5 and onward)
020:
021: print my_string[:len(my_string) - 1] #Hello Worl (From start to length of string minus one)
022: print my_string[len(my_string) - 1] #d (Only print the last letter)
023:
024:
025: #PS: Index 0 is the first letter.
026: #PPS: Lenght of string is outside of range. Since slicing start on index 0.
027: