Is there any way to change the nth byte of a file with a O(1) space and time complexity. I do know a way to read the nth byte (without loading to RAM) with a O(n) time complexity by adding a newline every x characters and iterating over the lines in the file.
Notes: I have a .txt file ~1GB in size using latin-1 encoding (So each character taking up 1byte).
CodePudding user response:
As already mentioned in the comments, you can change the current file position to a specific location within the file, then you can overwrite the next byte.
with open("blankpaper.txt", "wb") as f:
# write a few bytes to file
f.write(b"abcdefg")
# changes file position
f.seek(3)
# overwrites the fourth byte
f.write(b"g")
The resulting file has contents b"abcgefg"
.