[Tutor] I am a friendly inoffensive non-commercial subject li
ne
alan.gauld@bt.com
alan.gauld@bt.com
Tue, 13 Aug 2002 18:25:51 +0100
> The current high-level file commands force you to deal with a
> class of questions that the Python Elves usually keep
> submerged:
Yep, so maybe there's a reason...
> Of course it's good to have the choice of low-level,
> byte-by-byte control, but that is what the os module is for.
> Python was being invented, throwing a thin wrapper around
> the C functions that everybody involved knew was a good idea
Actually altho' Python does wrap the C stuff the file
methods are very similar to every mainstream programming
language around from ADA to Lisp, to Smalltalk...
> We recognize two different types of flies:
>
> 1) "Normal" files which consist of lines, ...text
> 2) "Binary" files which consist of bytes.
Pascal kind of makes that distinction by having text
files as a special category. But binary files are
broken into myriad types... FILE OF <FOO>
> Now when we want to access a file, we don't "open" it -
> that's the Elves' job - we just get right down to it:
>
> filehandle = file('/home/scot/python/wetcat.text') or
> binhandle = binfile('flooddata.dat')
>
> With this type of file, we can iterate, splice, or index the content
> without having to explicitly tell the Elves that we want to
> read or write or whatnot:
Thats actually quite tricky to do. Why not try implememting
the interface in Python to see whats involved.... I had to
build a "generic" file class in C++ once - it grew to
well over 1000 lines!
One problem is that under the covers you have to figure out predictively
what mode to open the raw file in - what
does the user want to do with it. Otherwise you have to
open/close the file after each operation and keep track
of where the last access was etc etc...
> >>>filehandle[2]
> 'drip drip drip'
> >>>filehandle[0:2]
> ['drip', 'drip drip']
Not too hard if its text and you assume line by line
access rather than characters, binary presumably
returns bytes?
> Since we have direct (random) access with splices and
> indices, we don't need to 'seek' and 'tell' anymore,
Ah, but now try implementing that on a binary file.
But I guess you could just seek(0) after each
operation... or could you? It might depend on the
current mode...
> Reading is easy; writing gets you into trouble,
Yes, especially with indexing type access.
BTW Have you looked at the fileinput module which
does a little bit of what you want I think....
Alan g.