Python

Web server on port 8000 for your current folder

python -c "import SimpleHTTPServer;SimpleHTTPServer.test()"

Read an UTF-16 file

import codecs
codecs.open(filePath, "r", "utf-16")

UTF-8 source code

# -*- coding: utf-8 -*-

read file line by line

import sys
 
f = open(sys.argv[1])
for l in f:
	l = l.strip()
	...

ASCII value of a char

ord("a")

list mapping

[e.replace("'", "''") for e in l]

regular expressions

import re
reg = '^[0-9]*?[)\.-]'
p = re.compile(reg)
if p.match(str):		
	print re.sub(reg, '', str)
  sub(pattern, repl, string, count=0)
        Return the string obtained by replacing the leftmost
        non-overlapping occurrences of the pattern in string by the
        replacement repl.  repl can be either a string or a callable;
        if a callable, it's passed the match object and must return
        a replacement string to be used.

syntax reference: http://www.python.org/doc/2.3/lib/re-syntax.html

csv export

rows = []
rows.append(['vanessa', 'carlton'])
rows.append(['nelly', 'furtado'])
 
import csv
csv.register_dialect('mycsv', quoting = csv.QUOTE_ALL)
writer = csv.writer(open("file.csv", "wb"), 'mycsv')
 
writer.writerows(rows)

file.csv

"vanessa","carlton"
"nelly","furtado"

ref:

build SQL insert query string

# SQL fields
l = []
l.append(['section', 'art_gallery'])
l.append(['category', 'just a test'])
l.append(['type', 'image'])
 
# build SQL query
keys = [e[0] for e in l]
values = [e[1] for e in l]
values = [e.replace("'", "''") for e in values]
query = """insert into `media` (`%s`) values ('%s');""" % ("`, `".join(keys), "', '".join(values), )
 
print query

recursively parse directory

import os
 
for dirname, dirnames, filenames in os.walk('.'):
    for subdirname in dirnames:
        print os.path.join(dirname, subdirname)
    for filename in filenames:
        print os.path.join(dirname, filename)

Source: http://stackoverflow.com/questions/120656/directory-listing-in-python

read photo EXIF data

exif.py

import EXIF
f = open('photo.jpg', 'rb')
 
tags = EXIF.process_file(f)
print tags

Source: http://www.dudek.org/blog/154

 

Feedback

You're going to need to escape each of the values for the query generator. In it's current state it's susceptible to query injection attacks.
matt
August 26, 2010
#1
You're going to need to escape each of the values for the query generator. In it's current state it's susceptible to query injection attacks.
matt
August 26, 2010
#2