Home > Back-end >  python file how to delete the last line
python file how to delete the last line

Time:01-03

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 !

CodePudding user response:

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

CodePudding user response:

You can do something like this, using read().splitlines()

file_name = "file.txt"
data = open(file_name).read().splitlines()
with open(file_name, "w") as fh:
    for idx, line in enumerate(data):
        if idx >= 3:
            break
        fh.write(f"{line}\n")

and if you would like to only remove the last line you can instead type: if idx >= len(data) - 1:

CodePudding user response:

The most effiecient way to get rid of last line will be using subproccess module with 'head' command to get rid of the last line:

Input:

Line_1
Line_2
Line_3
Line_4

Code:

import subprocess

filename = 'file.txt'

line = subprocess.check_output(['head', '-n', '-1', filename])

line = line.decode('utf-8')

print(line)

Output:

Line_1
Line_2
Line_3
  • Related