Plutonic Rainbows

Reading Files and Numbering Lines

Python can read other files (as we know) but it can also rewind and print the lines again. Just define a function called rewind and you're all set to go.

from sys import argv

script, input_file = argv

def print_all(f):
    print f.read()

def rewind(f):
    f.seek(0)

def print_a_line(line_count, f):
    print line_count, f.readline()

current_file = open(input_file)

print "First, let's print the whole file:\n"
print_all(current_file)

print "Now rewind."
rewind(current_file)

print "Let's print three lines:"

current_line = 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

Creating Lists

Looking through lists again. How to create a simple list and assign it to a variable.

albums = ['Meddle', 'Atom Heart Mother', 'Dark Side of the Moon', 'Wish You Were Here', 'The Wall']

for albums in albums:
    print "An album by Pink Floyd: %s" % albums

String Length

Python's len() method can be used to easily find the length of a string. It's a simple and quick way to measure the length of a string (the number of characters) without having to write a lot of code. The syntax for using the len() method is fairly straightforward, and hard to mess up. Even I can manage it.

from sys import argv

script, file = argv

source = open(file)
indata = source.read()

print "The file called '%s' is %s bytes in length." % (file, len(indata))

Remember that len() calculates the string so it can be used for characters too. You could ask Python to count the letters in a word or sentence.

Music for Installations

Out next Friday (May 4th) is the long-awaited Brian Eno box set, featuring some previously unreleased music; despite what the PR machine might say. You can order it from Amazon or Bleep.

Error

Did anyone spot the glaring error in the last script? It misses the len(indata) which calculates the file size. I have corrected that now. Thanks to everyone who contacted me.