Search code examples
pythonlistoperating-systemreadfilewritefile

python file how to delete the last line


I have a file that contains:

Line_1
Line_2
Line_3
Line_4

I want to delete the last line of the file Line_4 while opening the file, NOT using python list methods, and as follwoing:

with open('file.txt', 'r+') as f:
    lines = f.readlines()
    if len(lines) > 3:
        f.seek(0)
        for i in lines:
            if i != 4:
                f.write(i)
        f.truncate()

The above solution is not working. I also have used the os.SEEK_END as follwoing:

with open('file.txt', 'r+') as f:
    lines = f.readlines()
    if len(lines) > 3:
        f.seek(0, os.SEEK_END)
        f.truncate()

But, it is not working as well !


Solution

  • 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())