简体   繁体   中英

How to change the nth byte in a file without loading it into RAM using Python

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).

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" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM