Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 True:
        if f.readline():
            previous_position = current_position
            current_position = f.tell()
        else:
            break
    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:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading