Changing a line in a text file

Michael Hoffman cam.ac.uk at mh391.invalid
Mon Apr 25 05:52:48 EDT 2005


kah wrote:
> How do I change a line in a file??
> 
> For example I have the follwing text in my file:
> 
> line1
> line2
> line3
> line4
> 
> How do I replace 'line2' with 'newline'. Since the write operation in
> python will  overwrite everything.

This is the best I can figure out what you mean:

lines = []
for line in file("myfile.txt"):
     if line == "line2\n":
         line = "newline\n"
     lines.append(line)

file("myfile.txt", "W").writelines(lines)

-- 
Michael Hoffman



More information about the Python-list mailing list