Re: File Handling - Some Help Needed

Ken Manheimer (klm@NIST.GOV)
Thu, 13 Apr 1995 18:30:55 -0400 (EDT)

On Thu, 13 Apr 1995, Alan Sandercock wrote:

> Here is a rather simple question and I almost fell embarrassed about
> asking it but I can't find the information in the documentation. How
> do you operate on files with Python? Since it is so obvious a
> question it should be in the docs somewhere but the tutorial doesn't
> seem to mention anything about file handles, etc, even though it goes

I noticed the same thing when i was first learning python, and i think it
is a serious oversight in the tutorial. I think i mentioned it at some
point, but then forgot about the issue as i went forward. It is, i think,
such a fundamental issue that absence of coverage for it musta snuck by,
all this time.

The subject is introduced cursorily in the ref manual and then is covered
in full detail in the library reference manual. The libref 'File Objects'
section describes use of file objects, and the 'Built-in Functions'
section contains a description of the 'open' function by which you create
one.

Wanting to give a bit info to help you get started, here is an example
showing a few ways to read from a file.

vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
try: motd = open('/etc/motd', 'r')
except IOError:
print 'open failed'
else:
while 1:
line = motd.readline()
if not line: break
print ':' + line[:-1] + ':'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

(The '[:-1]' on the last line is to strip off the newline character from
each read line, before it is printed.)

Alternately, you could use readlines to do it more wholesale:

vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
try: motd = open('/etc/motd', 'r')
except IOError:
print 'open failed'
else:
for line in motd.readlines():
print ':' + line[:-1] + ':'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

There are, of course, other approaches to this, some of them spiffy in
their own ways. I think python is really great, and hope the oversight in
the documention on file objects won't discourage you...

(And i hope that oversight gets corrected, sometime soon.)

ken
ken.manheimer@nist.gov, 301 975-3539