Reading files, splitting on a delimiter and newlines.

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Jul 22 06:54:32 CEST 2007


chrispwd at gmail.com a écrit :
> Hello,
> 
> I have a situation where I have a file that contains text similar to:
> 
> myValue1 = contents of value1
> myValue2 = contents of value2 but
>                         with a new line here
> myValue3 = contents of value3
> 
> My first approach was to open the file, use readlines to split the
> lines on the "=" delimiter into a key/value pair (to be stored in a
> dict).
> 
> After processing a couple files I noticed its possible that a newline
> can be present in the value as shown in myValue2.
> 
> In this case its not an option to say remove the newlines if its a
> "multi line" value as the value data needs to stay intact.
> 
> I'm a bit confused as how to go about getting this to work.
> 
> Any suggestions on an approach would be greatly appreciated!
> 

data = {}
key = None
for line in open('yourfile.txt'):
     line = line.strip()
     if not line:
         # skip empty lines
         continue
     if '=' in line:
         key, value = map(str.strip, line.split('=', 1))
         data[key] = value
     elif key is None:
         # first line without a '='
         raise ValueError("invalid format")
     else:
        # multiline
        data[key] += "\n" + line


print data
=> {'myValue3': 'contents of value3', 'myValue2': 'contents of value2 
but\nwith a new line here', 'myValue1': 'contents of value1'}

HTH



More information about the Python-list mailing list