Delete the last line of a txt file

Asked

Viewed 1,138 times

2

I need to delete the last line of a txt file.

I found the last line like this:

with open('arquivo.txt', 'r') as content:
    line = content.readlines()
    last_line = line[len(line)-1]

Note: you can change the read mode in the open function.

  • 2

    You need to solve this necessarily with Python?

4 answers

3

If it is a very large file, see this form, it reads the file backwards in binary until it finds the character of the last line. Then convert him.

import os

with open('arquivo.txt', 'rb') as f:
   f.seek(-2, os.SEEK_END)
   while f.read(1) != b'\n':
      f.seek(-2, os.SEEK_CUR) 
   print(f.readline().decode())

3


To work with large files this is a possible solution:

import os

with open('arquivo.txt', 'r+', encoding = "utf-8") as arquivo:

    # Move o ponteiro (similar a um cursor de um editor de textos) para o fim do arquivo. 
    arquivo.seek(0, os.SEEK_END)

    # Pula o ultimo caractere do arquivo
    # No caso de a ultima linha ser null, deletamos a ultima linha e a penúltima
    pos = arquivo.tell() - 1

    # Lê cada caractere no arquivo, um por vez, a partir do penúltimo
    # caractere indo para trás, buscando por um caractere de nova linha
    # Se encontrarmos um nova linha, sai da busca
    while pos > 0 and arquivo.read(1) != "\n":
        pos -= 1
        arquivo.seek(pos, os.SEEK_SET)

    # Enquanto não estivermos no começo do arquivo, deleta todos os caracteres para frente desta posição
    if pos > 0:
        arquivo.seek(pos, os.SEEK_SET)
        arquivo.truncate()
  • Original answer: https://stackoverflow.com/a/10289740/1452488

1

If we happen to be on *Nix systems, a solution would be

head -n -1 file > novo

... but does not use Python.

0

In this way:

line = file.readlines()
line = lines[:-1]
  • 3

    Note that this will load the entire contents of the file in memory. If you are working with large files, this could be a serious problem.

  • 1

    This is one of the problems, the file is large and need to minimize the use of resources.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.