[Pythonmac-SIG] Frustration building, please help...

David Glasser me@davidglasser.net
Thu, 1 Nov 2001 16:38:16 -0500


>Well, so far Python hasn't been too hard to start learning, except that it
>doesn't really seem to work. I'm working on a Mac G4 OS9 and can't even seem
>to read, write, or manipulate files. Here's what I get, just trying to do
>some simple stuff right out of the tutorial...

I'm not quite sure what exactly you're trying to do.  However, I'll note
that using open modes like 'r+' in any  language is usually not "some
simple stuff".  I'll try to walk through what you have.

Note that when using 'r+' mode, the file is opened with the current
position at the beginning; both reading and writing advances this current
position.  This means that after you write something, trying to read from
the file gives you what is *after* what you just wrote.  You can find out
your position in the file with f.tell, and set it with f.seek.

>>>> f=open('blah', 'r+')

You open a preexisting file.

>>>> f.write('testing 123')

You change its first eleven bytes, leaving your position after those bytes.

>>>> f.read()
>Traceback (most recent call last):
>  File "<input>", line 1, in ?
>IOError: (0, 'Error')

I'm not sure why this happens.

>>>> f.readline()
>''

You read to the end of the line, which seems to be nothing (i.e., you were
at the end of the line already).

>>>> f.write('testing again')

You change thirteen more bytes.

>>>> f.readline()
>'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0
>0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0
>0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0
>0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0
>0\x00\x00\x00\x00\x00\x00\x00\x00widths\x06\x00\x00\x00\x06\xd0\x00\x00\x17\
>xa0\x12m<\x81\x12n\x13X\x12mO\xb8lls\x01\x00\x00\x00Ws\n'

You read the (binary, it seems) file up untill the next newline.


You might want to start with text files instead of binary files, and avoid
'r+' mode unless it is absolutely necessary.

--David Glasser

me@davidglasser.net