String from File -> List without parsing

John Machin sjmachin at lexicon.net
Mon Sep 5 00:26:30 CEST 2005


Gregor Horvath wrote:
> Hi,
> 
> given the dynamic nature of python I assume that there is an elegant 
> solution for my problem, but I did not manage to find it.
> 
> I have a file that contains for example on line:
> ['147', '148', '146']
> when I read the file
>  f = file("I050901.ids").readlines()

Y3K bug alert :-)

> I have a string
> f[0] == "['147', '148', '146']"

The last (or sole) line is highly likely to be "['147', '148', 
'146']\n". If there are multiple lines in the file, all but the last 
will definitely have "\n" at the end.

> How can I turn this string into a list
> li == ['147', '148', '146']
> without parsing?

Something like this:

 >>> def munch(astrg):
...    return [x[1:-1] for x in astrg.rstrip("\n")[1:-1].split(", ")]
...
 >>> munch("['147', '148', '146']")
['147', '148', '146']
 >>> munch("['147', '148', '146']\n")
['147', '148', '146']
 >>> munch("['147']\n")
['147']
 >>> # Warning: various flavours of "nothing" give the same result:
 >>> munch("['']\n")
['']
 >>> munch("[]\n")
['']
 >>> munch("\n")
['']
 >>>

This assumes that the contents are no more complicated than in your example.

Some notes:

(1) You neither want nor need to use eval.

(2) What is creating files like that? If it is a Python script, consider 
writing them using the csv module; that way, other software can read 
them easily.

HTH,
John



More information about the Python-list mailing list