Skip to content

Instantly share code, notes, and snippets.

View seanh's full-sized avatar

Sean Hammond seanh

View GitHub Profile
@seanh
seanh / gist:232829
Created November 12, 2009 11:19
Writing text files in Python
# Write mode creates a new file or overwrites the existing content of the file.
# Write mode will _always_ destroy the existing contents of a file.
try:
# This will create a new file or **overwrite an existing file**.
f = open("file.txt", "w")
try:
f.write('blah') # Write a string to a file
f.writelines(lines) # Write a sequence of strings to a file
finally:
f.close()
@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 / 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