how do i delete my last line?

Basically, if you want to delete Last line from file using .truncate() you can just save previous position before retrieving next line and call .truncate() with this position after you reach end of file:

with open("file.txt", "r+") as f:
    current_position = previous_position = f.tell()
    while f.readline():
        previous_position = current_position
        current_position = f.tell()
    f.truncate(previous_position)

If you need just need to remove all lines after certain index you can just retrieve new line this amount of times and call .truncate() on current position:

index = 4
with open("file.txt", "r+") as f:
    for _ in range(index - 1):
        if not f.readline():
            break
    f.truncate(f.tell())

Or shorter:

lines_to_keep = 3
with open("file.txt", "r+") as f:
    while lines_to_keep and f.readline():
        lines_to_keep -= 1
    f.truncate(f.tell())

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top