Code snippets‎ > ‎Scripting‎ > ‎


All kinds of python snippets.

For loops

Page 24 of the Python pocket reference from O'Reilly:
[x**2 for x in range(5) if (x%2)]

Implicit lists, using only iterators:
for x_sqr in (x**2 for x in range(5) if (x%2)):
  print x_sqr

Read a csv file

import csv
reader = csv.reader(open('logfile_04_03_06_20.csv'), delimiter=",")
for line in reader:
  print ";".join(line)


Make a CSV-string from a list:
Get a sub-string:
a = "Hello world";
a[6:] == "world"


Check if a file exists: os.path.exists(output_file)

Check if a file is empty: os.stat(output_file)[6] == 0

List the contents of a directory

for filename in files:
  print filename

Rename files recursively in all subdirectories

import os, re
for root, dirs, files in os.walk("."):
    for name in files:
        if"_3", name):
            output_file = re.sub("_3", "_2", name)
            os.rename(root+"/"+name, root+"/"+output_file)

Regular expessions

Substitute a string:
import re
print re.sub('Hello', "Good bye", "Hello world!")

Replacing all occurences in a file:
import fileinput
def replace(files, search_expr, replace_expr):
  for line in fileinput.input(files, inplace = 1):
    print line.replace(search_expr, replace_expr),
replace(["a.txt", "b.txt"], ",", ".")