[Tutor] file opening and errors.

Andrew P grouch at gmail.com
Thu Oct 20 18:48:07 CEST 2005

It's not in direct answer to your question, but a real short answer is
"Python doesn't need 'or die' here."  It throws exceptions gleefully
whenever it encounters an error:

>>> f = open('no_such_file')

Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
IOError: [Errno 2] No such file or directory: 'no_such_file'

>>> import os
>>> os.rmdir('/squeak')

Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
OSError: [Errno 41] Directory not empty: '/squeak'

This behavior highlights one of the philosophical differences between
the languages.

Another reversal of stances to keep in mind is that variables are
local by default in Python, and global by default in Perl.

These are also two of my absolute favorite differences.  Silent errors
and global variables never sat well with me.  Die and my are the
general use cases :)

Good luck,


On 10/20/05, Dan Klose <dklose at nimr.mrc.ac.uk> wrote:
> Hi,
> I usually use perl but fancy a bit of a change so have started playing
> with python.
> using perl to open a file or directory I usually use:
> open(FILE, $file) or die "Error: $!\n";
> The $! is a perl variable that holds an error should the open fail,
> example being : "No such file or directory".
> With python I have use a try except block but I have no idea how I would
> get the same warning from python as I would from perl (the reason for
> the exception), I am not even sure if this is possible (I assume it must
> be) as google searching has been fruitless.
> Thanks for any help, pointers and suggestions.
> Dan.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list