Reading files, splitting on a delimiter and newlines.

Hendrik van Rooyen mail at
Thu Jul 26 08:45:55 CEST 2007

: < at> Wrote:

> On Jul 25, 10:46 am, chris... at wrote:
> > 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!
> I'm confused. You don't want the newline to be present, but you can't
> remove it because the data has to stay intact? If you don't want to
> change it, then what's the problem?

I think the OP's trouble is that the value he wants gets split up by the
newline at the end of the line when he uses readline().

One can try adding the single value to the previous value in the previous
key/value pair when the split does not yield two values - a bit hackish,
but given structured input data it might work.

- Hendrik

More information about the Python-list mailing list