[Tutor] reading file, adding to each line, writing file

A.T.Hofkamp a.t.hofkamp at tue.nl
Wed Feb 4 15:43:47 CET 2009


David wrote:
> line = infile.readline()    # Invokes readline() method on file
> while line:
>     outfile.write(line),    # trailing ',' omits newline character
>     line = infile.readline()

The 'while' loop can be replaced by a 'for' loop, like

for line in infile:
   outfile.write(line)

> 
> infile.close()
> outfile.close()
> 
> </code>
> 
> As I said, before writing to file "pyout" I would like to append the 
> string " -d" to each line. But how, where? I can't append to strings 
> (which the lines gained with infile.readline() seem be), and my trial 
> and error approach has brought me nothing but a headache.

readline() literally reads a line, including the terminating \n at the end.

(the end-of-file indication uses the empty string. By returning the 
terminating \n as well, an empty line becomes a "\n" string, so you can 
distinguish between both cases).



The simplest solution would be to construct a new line from the old one 
directly below the 'while', for example

line2 = line[:-1] + " -d\n"

followed by writing line2 to disk.


The question that arises however is, what should be done with a line like

"bla bla                 \n"

Do you want

"bla bla                 -d\n"

or do you want

"bla bla -d\n"

here?

If the latter, you may want to use str.rstrip() that deletes all white-space 
from the end of the line, like

line2 = line.rstrip() + " -d\n"


Sincerely,
Albert



More information about the Tutor mailing list