Reputation: 311
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)
Upvotes: 1
Views: 133
Reputation: 43495
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!"
Upvotes: 1
Reputation: 42748
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)
Upvotes: 2