writing from file into dictionary

Brad Hards bhards at bigpond.net.au
Mon Nov 11 08:23:21 EST 2002


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Tue, 12 Nov 2002 00:01, Alex Martelli wrote:
<snip>
> > When used this way, open() or file(), takes a default of opening in read
> > only mode, with unbuffered I/O.
>
> Yes, and no.  Yes, read-only mode (and text-mode too, on platform where
> it matters); but no, unbuffered I/O is not the default -- that would damage
> performance substantially in this default-openiong case.
OK. I was working off the help() text. My newbie-after-midnight brain saw that 
you can specify the mode as unbuffered by assigning the third element to 
zero. I couldn't find the code that implemented it, so I'm not sure what the 
real default is. Have to check tomorrow.
<snip>

> Indeed: only Python 2.2 and later.  In earlier versions, you could use:
>
> for line in open('thefile').readlines():
>
> as long as the file isn't too large to fit all in memory at once
> comfortably. For potentially-huge files in old Python versions, you'd need
> to use less legible and handly idioms, which is why the new one was added
> in 2.2.
Documentation shows a few others (eg xreadlines()?), but I'm really only 
interested in newer versions of python.
<snip>
> > Having got our list of three items, we create a slice consisting of the
> > first two items. This sliced list is then unpacked into two variables -
> > "head" and "rewrite". You could also use:
> > head, rewrite = filter(None, line.split(':',2))
> > but I guess that is less efficient, otherwise Alex would have used it.
>
> That would never occur to me -- there are no specs about skipping
>
> empty pieces; and it would fail just about every time, e.g.:
> >>> line = 'a:b:\n'
> >>> head, rewrite = filter(None, line.split(':',2))
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: unpack list of wrong size
<snip>

Not sure what I was thinking about when I came up with this.
I _did_ test it, on a string which didn't have anything trailing the second 
colon.  Someone showed me this for another purpose (splitting up a list of 
domain names, which might be fully-qualified), and "when the only tool you 
have is a hammer..."

Thanks again for your time. I'll get there eventually...

Brad

- -- 
http://linux.conf.au. 22-25Jan2003. Perth, Aust. I'm registered. Are you?
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE9z69JW6pHgIdAuOMRAkC5AJ4oszN8Y5SLCISvUS/KZEcleUVxjQCfVY2w
YqBJTfmK7oydM0wL3qX7VrU=
=28sY
-----END PGP SIGNATURE-----





More information about the Python-list mailing list