Skip to content

Instantly share code, notes, and snippets.

Avatar

Sean Hammond seanh

View GitHub Profile
@seanh
seanh / gist:232829
Created Nov 12, 2009
Writing text files in Python
View gist:232829
# 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 Aug 10, 2009
Read a file in Python
View gist:165218
# 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
Get a Swing GUI up and running. (Handy for testing swing components.)
View MyClass.java
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 Mar 18, 2009
Recursively walk a directory in Python with os.walk.
View walk.py
"""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
You can’t perform that action at this time.