Monday, March 23, 2009

Python Notes – 7 : Files & directories

Welcome to our seventh note in our Python learning process. This note will talk specifically about files, directories, and exceptions.

Files

Opening a file creates a file object. Syntax is like that:

>>> f = open("test.dat","w")

>>> print f

<open file 'test.dat', mode 'w' at fe820>

The first parameter to open is the file name, the second parameter is the mode. Modes are: w for write, r for read.

To write data in the file we invoke the write method on the file object:

>>> f.write("Now is the time")

>>> f.write("to close the file")

After we done we can close the file like that:

>>> f.close()

The read method reads data from the file. With no arguments, it reads the entire contents of the file:

>>> text = f.read()

>>> print text

Now is the time to close the file

read can also take an argument that indicates how many characters to read.

If not enough characters are left in the file, read returns the remaining characters. When we get to the end of the file, read returns the empty string:

>>> print f.read(5)

Now i

>>> print f.read(1000006)

s the timeto close the file

>>> print f.read()

>>>

The write method write data to the file. It takes strings only.

>>> x = 52

>>> f.write (str(x))

Directories

When you create a new file by opening it and writing, the new file goes in the current directory (wherever you were when you ran the program). Similarly, when you open a file for reading, Python looks for it in the current directory. If you want to open a file somewhere else, you have to specify the path to the file, which is the name of the directory (or folder) where the file is located:

>>> f = open("/usr/share/dict/words","r")

>>> print f.readline()

Whatever exist

glob module

Returns filenames in a directory that match a pattern.

import glob

a = glob.glob("*.html")

b = glob.glob("image[0-5]*.gif")

Pattern matching is performed using rules of Unix shell. Tilde (~) and variable expansion is not performed.

fnmatch module

Matches filenames according to rules of Unix shell.

import fnmatch

if fnmatch(filename,"*.html"):

...

Case-sensitivity depends on the operating system.

Other File-Related Modules

  • fcntl : Provides access to the fcntl() system call and file-locking operations

import fcntl, FCNTL

fcntl.flock(f.fileno(),FCNTL.LOCK_EX) # Lock a file

  • tempfile : Creates temporary files
  • gzip : Creates file objects with compression/decompression. Compatible with the GNU gzip program.

import gzip

f = gzip.open("foo","wb")

f.write(data)

Exceptions

Whenever a runtime error occurs, it creates an exception. Usually, the program stops and Python prints an error message.

>>> print 55/0

ZeroDivisionError: integer division or modulo

We can handle the exception using the try and except statements.

filename = raw_input('Enter a file name: ')

try:

f = open (filename, "r")

except:

print 'There is no file named', filename

The try statement executes the statements in the first block. If no exceptions occur, it ignores the except statement. If any exception occurs, it executes the statements in the except branch and then continues.

If your program detects an error condition, you can make it raise an exception.

def inputNumber () :

x = input ('Pick a number: ')

if x == 17 :

raise 'BadNumberError', '17 is a bad number'

return x

The raise statement takes two arguments: the exception type and specific

information about the error. And here how the previous example appears:

>>> inputNumber ()

Pick a number: 17

BadNumberError: 17 is a bad number

This note talked about files, directories, and exceptions. The next note will go into the object oriented features of Python.

Python Notes – 6 : Tuples & Dictionaries

Welcome to our sixth note in our Python learning process. In this note we will talk about tuples and dictionaries.

Tuples

Tuples are similar to lists but its elements can't be modified. Syntactically, a tuple is a comma-separated list of values:

>>> tuple = 'a', 'b', 'c', 'd', 'e'

Although it is not necessary, it is conventional to enclose tuples in parentheses:

>>> tuple = ('a', 'b', 'c', 'd', 'e')

To create a tuple with a single element, we have to include the ¯nal comma:

>>> t1 = ('a',)

>>> type(t1)

<type 'tuple'>

Without the comma, Python treats ('a') as a string in parentheses:

>>> t2 = ('a')

>>> type(t2)

<type 'string'>

Tuple assignment

Tuples assignment could be used to perform multiple assignments in one statement. For example, to swap a and b we can make it like that:

>>> a, b = b, a

The left side is a tuple of variables; the right side is a tuple of values. Each value is assigned to its respective variable.

Dictionaries

Dictionaries are like lists and tuples in that all of them are compound types.

Dictionaries are different than lists and tuples in that it can use any immutable type as an index not only integers like tuples and lists. Dictionaries are not ordered.

To create an empty dictionary and then add elements to it:

>>> eng2sp = {}

>>> eng2sp['one'] = 'uno'

>>> eng2sp['two'] = 'dos'

>>> print eng2sp

{'one': 'uno', 'two': 'dos'}

You can also create the dictionary by providing a list of key-value pairs:

>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}

>>> print eng2sp

{'one': 'uno', 'three': 'tres', 'two': 'dos'}

Dictionary Operations

del statement removes a key-value pair from a dictionary.

>>> inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}

>>> print inventory

{'oranges': 525, 'apples': 430, 'pears': 217, 'bananas': 312}

>>> del inventory['pears']

>>> print inventory

{'oranges': 525, 'apples': 430, 'bananas': 312}

The len function also works on dictionaries; it returns the number of key-value pairs:

>>> len(inventory)

4

Dictionary methods

The keys method takes a dictionary and returns a list of the keys.

>>> eng2sp.keys()

['one', 'three', 'two']

The values method is similar; it returns a list of the values in the dictionary:

>>> eng2sp.values()

['uno', 'tres', 'dos']

The items method returns both, in the form of a list of tuples|one for each key-value pair:

>>> eng2sp.items()

[('one','uno'), ('three', 'tres'), ('two', 'dos')]

The method has_key takes a key and returns true (1) if the key appears in the dictionary:

>>> eng2sp.has_key('one')

1

>>> eng2sp.has_key('deux')

0

Aliasing and copying

Dictionaries are objects that can be aliased like that:

>>> opposites = {'up': 'down', 'right': 'wrong', 'true': 'false'}

>>> alias = opposites

Or copied to a new fresh copy like that:

>>> copy = opposites.copy()

This note completed the compound data types talk we started before with lists. Lists, tuples, and dictionaries are the compound data types that Python provides. You can use them as is or you can use them to build a more complex data types and containers.

Python Notes – 5 : Objects & Values

Welcome to our fifth note in our Python learning process. In this note we will talk about one of the core concepts of the Python language semantics .

Objects and Values

An object is something a variable can refer to. Every object has a unique identifier, which we can obtain with the id function.

>>> a = "banana"

>>> b = "banana"

>>> id(a)

135044008

>>> id(b)

135044008

Interestingly, lists behave differently. When we create two lists, we get two

objects:

>>> a = [1, 2, 3]

>>> b = [1, 2, 3]

>>> id(a)

135045528

>>> id(b)

135041704

Since both a and b refer to the same object, changes made to the object through one of them appear when you access the object through the other. This is called aliasing.

>>> a = [1, 2, 3]

>>> b = [1, 2, 3]

>>> b[0] = 5

>>> print a

[5, 2, 3]

This brief note is just to differentiate between values and objects. Objects not only the instances we create of classes, some language types treated as objects and others treated as values.

We will discuss object oriented in a separate note within days.

Python Notes – 4 : Lists

Welcome to our third note in our Python learning process. In this note we will talk mainly about lists, its functions and how to use it.

Lists - Creation

A list is an ordered set of values, where each value is identified by an index. The values that make up a list are called its elements. You could create it like:

>>> X = [12, 56, 87]

>>> print X

[12, 56, 87]

>>> Y = ["one", "three", "five"]

>>> print Y

["one", "three", "five"]

The list elements don't have to be the same type.

["hello", 2.0, 5, [10, 20]]

A list within another list is said to be nested.

Another way of creating special list of consecutive integers:

>>> range(1,5)

[1, 2, 3, 4]

If there is no start of the range, it will create starting from the 0

>>> range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

If there is a third argument, it specifies the space between successive values,

which is called the step size

>>> range(1, 10, 2)

[1, 3, 5, 7, 9]

Lists - Accessing elements

You access list elements by index. Indices starts with zero. Indices could be any integer expression.

>>> numbers = range(1,10)

>>> print numbers[0]

1

>>> print numbers[5-3]

3

Lists - Length

You can get the list length using len() method. Syntax like that:

>>> len(numbers)

9

Although a list can contain another list, the nested list still counts as a single

element. The length of this list is four:

['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]

Lists - operators

in is a boolean operator that tests membership in a sequence.

>>> horsemen = ['war', 'famine', 'pestilence', 'death']

>>> 'pestilence' in horsemen

1

>>> 'debauchery' in horsemen

0

Lists - for loops

The syntax is like:

for VARIABLE in LIST:

BODY

for horseman in horsemen:

print horseman

This is equivalent to:

i = 0

while i < len(LIST):

VARIABLE = LIST[i]

BODY

i = i + 1

Any list expression can be used in a for loop:

for number in range(20):

if number % 2 == 0:

print number

List - operations

The + operator concatenates lists:

>>> a = [1, 2, 3]

>>> b = [4, 5, 6]

>>> c = a + b

>>> print c

[1, 2, 3, 4, 5, 6]

Similarly, the * operator repeats a list a given number of times:

>>> [0] * 4

[0, 0, 0, 0]

>>> [1, 2, 3] * 3

[1, 2, 3, 1, 2, 3, 1, 2, 3]

The head function takes a list as a parameter and returns the first element.

>>> a = [1, 2, 3]

>>> head(a)

1

List - slices

>>> list = ['a', 'b', 'c', 'd', 'e', 'f']

>>> list[1:3]

['b', 'c']

>>> list[:4]

['a', 'b', 'c', 'd']

>>> list[3:]

['d', 'e', 'f']

>>> list[:]

['a', 'b', 'c', 'd', 'e', 'f']

List - deletion

del removes an element from a list:

>>> a = ['one', 'two', 'three']

>>> del a[1]

>>> a

['one', 'three']

You can use a slice as an index for del:

>>> list = ['a', 'b', 'c', 'd', 'e', 'f']

>>> del list[1:5]

>>> print list

['a', 'f']

  • Strings are lists and can be treated the same way you treat lists.

Nested lists

A nested list is a list that appears as an element in another list. In this list, the

three-eth element is a nested list:

>>> list = ["hello", 2.0, 5, [10, 20]]

To extract an element from the nested list, we can proceed in two steps:

>>> elt = list[3]

>>> elt[0]

10

Or we can combine them:

>>> list[3][1]

20

In this note we talked mainly lists which are very powerful feature in Python. We will continue our learning in the upcoming notes.