how to replace line on particular line in file[no need to write it back whole file again]
Peter J. Holzer
hjp-python at hjp.at
Fri Oct 12 14:55:41 EDT 2018
On 2018-10-11 13:57:57 +0200, Thomas Jollans wrote:
> There's no easy way to write to the middle of a file (though I think it
> can be done by mmap'ing a file)
#!/usr/bin/python3
import os
with open("foo.bin", "wb") as f:
f.write(b'abcdefghijklmnopqrstuvwxyz')
with open("foo.bin", "rb") as f:
print("-----")
for i, c in enumerate(f.read()):
print("%2d %2x" % (i, c))
with open("foo.bin", "r+b") as f:
f.seek(10, os.SEEK_SET)
f.write(b'000')
f.seek(20, os.SEEK_SET)
f.write(b'11')
f.seek(30, os.SEEK_SET)
f.write(b'2')
with open("foo.bin", "rb") as f:
print("-----")
for i, c in enumerate(f.read()):
print("%2d %2x" % (i, c))
Mmap doesn't allow you to do anything you can't do with normal file I/O.
It's just sometimes more convenient and/or performant.
> -- and even if you manage to do that,
> you'd have to write back anything after the changed line if the length
> of that line changed by as little as a byte.
This is correct.
hp
--
_ | Peter J. Holzer | we build much bigger, better disasters now
|_|_) | | because we have much more sophisticated
| | | hjp at hjp.at | management tools.
__/ | http://www.hjp.at/ | -- Ross Anderson <https://www.edge.org/>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20181012/452e8eda/attachment.sig>
More information about the Python-list
mailing list