[Tutor] Appending an extra column in a data file
Albert-Jan Roskam
fomcl at yahoo.com
Wed Apr 10 22:45:33 CEST 2013
> Subject: Re: [Tutor] Appending an extra column in a data file
>
<snip>
> The file you attached is a space-delimited text file. If you want to
> add a third column with the value '1.0' on every row you can just do:
>
> with open('old.dat') as fin, open('new.dat', 'w') as
> fout:
> for line in fin:
> fout.write(line[:-1] + ' 1.0\n')
Is that Python 3.x? I thought this "double context manager" could only be done with contextlib.nested, e.g.:
>>> with contextlib.nested(open(fn, "rb"), open(fn[:-4] + "_out.dat", "wb")) as (r, w):
... for inline in r:
... w.write(inline + " " + "somevalue" + "\n")
Your code looks cleaner though.
Regards,
Albert-Jan
More information about the Tutor
mailing list