Last active
January 23, 2018 07:16
-
-
Save xtendo-org/8a9fb121172f25339c78d5f8139c0876 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
CHUNK_SIZE = 1024 | |
def remove_last_line(path): | |
with open(path, 'rb+') as f: | |
def process_chunk(base_offset, chunk): | |
try: | |
f.seek(base_offset + chunk.rindex(b'\n'), os.SEEK_SET) | |
except ValueError: | |
return False | |
f.truncate() | |
return True | |
f.seek(0, os.SEEK_END) | |
pos = f.tell() - 1 | |
f.seek(pos, os.SEEK_SET) | |
last_char = f.read(1) | |
if last_char == b'\n': | |
f.seek(pos, os.SEEK_SET) | |
f.truncate() | |
while True: | |
if pos < CHUNK_SIZE: | |
f.seek(0, os.SEEK_SET) | |
process_chunk(0, f.read(pos)) | |
break | |
pos -= CHUNK_SIZE | |
f.seek(pos, os.SEEK_SET) | |
if process_chunk(pos, f.read(CHUNK_SIZE)): | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment