Skip to content

Instantly share code, notes, and snippets.

View seanh's full-sized avatar

Sean Hammond seanh

View GitHub Profile
@seanh
seanh / gist:165218
Created August 10, 2009 14:11
Read a file in Python
# The built-in function `open` opens a file and returns a file object.
# Read mode opens a file for reading only.
try:
f = open("file.txt", "r")
try:
# Read the entire contents of a file at once.
string = f.read()
# OR iterate over the file line-by-line:
for line in f:
# Do something with line.
@seanh
seanh / MyClass.java
Created May 25, 2009 15:22
Get a Swing GUI up and running. (Handy for testing swing components.)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyClass {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
@seanh
seanh / formatFilename.py
Created April 11, 2009 18:30
Turn any string into a valid filename in Python.
def format_filename(s):
"""Take a string and return a valid filename constructed from the string.
Uses a whitelist approach: any characters not present in valid_chars are
removed. Also spaces are replaced with underscores.
Note: this method may produce invalid filenames such as ``, `.` or `..`
When I use this method I prepend a date string like '2009_01_15_19_46_32_'
and append a file extension like '.txt', so I avoid the potential of using
an invalid filename.
@seanh
seanh / walk.py
Created March 18, 2009 14:26
Recursively walk a directory in Python with os.walk.
"""Recursively walk a directory with os.walk."""
import os
base_dir = '/home/seanh' # The directory to walk
for root, dirs, files in os.walk(base_dir):
print 'root: ',root
print ' dirs:'
for d in dirs:
print ' ',d