> 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
>

Hi David!
My solution of your problem would be the following:

>>> infile = open('step2', 'r')
>>> str = infile.read()
>>> infile.close()
>>> outfile = open('pyout', 'a')
>>> outfile.write(str.replace('\n', ' -d\n'))
>>> outfile.close()

hope helped
cheers!
Tiefeng Wu
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to