Python editing .txt file
MRAB
python at mrabarnett.plus.com
Wed Jun 16 19:35:01 EDT 2010
187braintrust at berkeley.edu wrote:
> From: MRAB <python at mrabarnett.plus.com
> <mailto:python at mrabarnett.plus.com>>
> To: python-list at python.org <mailto:python-list at python.org>
> Date: Wed, 16 Jun 2010 03:06:58 +0100
> Subject: Re: Python editing .txt file
> 187braintrust at berkeley.edu <mailto:187braintrust at berkeley.edu> wrote:
>
> I am trying to write a program in Python that will edit .txt log
> files that contain regression output from R. Any thoughts or
> suggestions would be greatly appreciated.
>
>
> How's this:
>
> input_file = open(input_path)
> output_file = open(output_path, "w")
> for line in input_file:
> if line.startswith("factor("):
> open_paren = line.find("(")
> close_paren = line.find(")")
> variable = line[open_paren + 1 : close_paren]
> output_file.write("*** Factors for %s ***\n" % variable)
> prefix = line[ : close_paren + 1]
> while line.startswith(prefix):
> line = input_file.readline()
> output_file.write(line)
> input_file.close()
> output_file.close()
>
>
> Thank you very much for your reply. This code works perfectly, except
> that the "line = input_file.readline()" part causes an error:
> "ValueError: Mixing iteration and read methods would lose data." I've
> been working on figuring out a work around. Do you have any ideas?
>
You could try replacing:
line = input_file.readline()
with:
line = input_file.next()
More information about the Python-list
mailing list