1

I've looking for here and there how to replace multiple lines in file with new ones but my code just add a line to very end of file. How to replace old line with new one in proper place ?

path = /path/to/file
new_line = ''
f = open(path,'r+b')
f_content = f.readlines()
line = f_content[63]
newline = line.replace(line, new_line)
f.write(newline)
f.close()

edited: path = /path/to/file path_new = path+".tmp" new_line = "" with open(path,'r') as inf, open(path_new, 'w') as outf: for num, line in enumerate(inf): if num == 64: newline = line.replace(line, new_line) outf.write(newline) else: outf.write(line) new_file = os.rename(path_new, path)

2
  • try using f_content.seek(n) , where n is the index of line . seek(0) takes to start of file. Commented Dec 31, 2015 at 9:48
  • Is the new line the same length as the old? Commented Dec 31, 2015 at 11:00

2 Answers 2

2

Most operating systems treat files as binary stream, so there is nothing like a line in a file. Therefore you have to rewrite the whole file, with the line substituted:

new_line = ''
with open(path,'r') as inf, open(path_new, 'w') as outf:
    for num, line in enumerate(inf):
        if num == 64:
           outf.write(new_line)
        else:
           outf.write(line)
os.rename(path_new, path)
Sign up to request clarification or add additional context in comments.

2 Comments

if path_new and path are the same code just creates empty file
correct, because it is overwritten! You need a temporary second filename, say path_new = path + ".tmp".
1

In general, you have to rewrite the whole file.

The operating system exposes a file as a sequence of bytes. This sequence has a so-called file pointer associated with it when you open the file. When you open the file, the pointer is at the beginning. You can read or write bytes from this location, but you cannot insert or delete bytes. After reading or writing n bytes, the file pointer will have shifted n bytes.

Additionally Python has a method to read the whole file and split the contents into a list of lines. In this case this is more convenient.

# Read everything
with open('/path/to/file') as infile:
    data = infile.readlines()
# Replace
try:
    data[63] = 'this is the new text\n' # Do not forget the '\n'!
    with open('/path/to/file', 'w') as newfile:
        newfile.writelines(data)
except IndexError:
    print "Oops, there is no line 63!"

2 Comments

thank you so mach,Roland, it works at last! One more a little question: what syntax should be to replace 'this is the new text' with variable?
@AndriyKravchenko Just use data[63] = variable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.