0

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 !

zezo
  • 445
  • 4
  • 16
  • 1
    `f.readlines()` reads all lines, so your `f.seek()` is useless. – Olvin Roght Jan 03 '22 at 11:11
  • So, How would you find the `len` of the lines, to which you truncate ? – zezo Jan 03 '22 at 11:13
  • did you try this already? https://stackoverflow.com/a/10289740/16841774 – Akida Jan 03 '22 at 11:17
  • In the first option, i is a line iterator being compared against an integer. It should've been something like *for in range(len(lines)-1)* and then *if i<=3: f.write(lines[i])* – Jayvee Jan 03 '22 at 12:11

3 Answers3

1

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())
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
0

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:

ErikXIII
  • 557
  • 2
  • 12
0

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
NSegal
  • 56
  • 3