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

David ldl08 at gmx.net
Wed Feb 4 15:30:34 CET 2009


Hello everybody,

I have easily spent some four hours on this problem, and I am now asking 
for rescue.

Here is what I am trying to do: I have a file ("step2", with some 30 or 
so lines. To each line I would like to add " -d" at the end. Finally, I 
want to save the file under another name ("pyout".
So far I have managed to read the file, line by line, and save it under 
another name:

<code>

# add " -d" to each line of a textfile

infile = open("step2", 'r') # open file for appending
outfile = open("pyout","a") # open file for appending

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

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.

Thanks for your help!

David



More information about the Tutor mailing list