Parse file into array

Bengt Richter bokr at oz.net
Wed Nov 16 01:23:05 CET 2005


On 14 Nov 2005 13:48:45 -0800, "amfr" <amfr.org at gmail.com> wrote:

>I was wondering how i could parse the contents of a file into an array.
> the file would look something like this:
>
>gif:image/gif
>html:text/html
>jpg:image/jpeg
>...
>
>As you can see, it contains the mime type and the file extension
>seperated by commas, 1 per line.  I was wondering if it was possible to
>create and array like this:
>
>(Pseudocode)
>mimetypearray[gif] = "image/gif"
>mimetypearray[html] = "text/html"
>mimetypearray[jpg] = "image/jpeg"
>...
>
>I come from a PHP backround where I know this is possible, but I am new
>at Python.  Please disregard this if it is a stupid question.
>
Pretty much anything is possible in Python, if you can conceive it well enough ;-)

Assuming f is from f = open(yourfile), simulated with StringIO file object here,

 >>> from StringIO import StringIO
 >>> f = StringIO("""\
 ... gif:image/gif
 ... html:text/html
 ... jpg:image/jpeg
 ... """)

And assuming that there are no spaces around the ':' or in the two pieces,
but maybe some optional whitespace at either end of a line and \n at the end
(except maybe the last line), and no blank lines, you can get a dict mapping easily:

 >>> mimetypedict = dict(tuple(line.strip().split(':')) for line in f)

This gives you:
 >>> mimetypedict
 {'gif': 'image/gif', 'html': 'text/html', 'jpg': 'image/jpeg'}

Which you can access using the names as keys, e.g.,
 >>> mimetypedict['gif']
 'image/gif'

If you want to use bare names to access the info via an object, you can use the
dict info to create a class or class instance and give it the named attributes, e.g.
a class with the data as class variables is quick:

 >>> MTC = type('MTC',(), mimetypedict)
 >>> MTC.gif
 'image/gif'
 >>> MTC.jpg
 'image/jpeg'

Or you could substitute the mimetypedict expression from above to make another one-liner ;-)

Other ways of setting up your info are certainly possible, and may be more suitable,
depending on how you intend to use the info. As mentioned, the mimetypes module
may already have much of the data and/or functionality you want.

Regards,
Bengt Richter



More information about the Python-list mailing list