Delete a particular line from a . csv using Python

Asked

Viewed 2,587 times

0

What I would like to do is that when the user typed the name of a person who was inside the file. csv, his line and the lines of movies he evaluated were erased (I used an identifier for this), the code is this:

import csv

with open("arquivo.csv", "r") as arq:
linhas = csv.reader(arq, delimiter=";")
critico = input("Digite o nome do crítico que você deseja deletar..: ").capitalize()
for linha in linhas:
    tipo, identificador, nome, nota = linha
    if tipo == "C":
        if critico in linha:
            ident = linha[1]
            print(linha)

    if tipo == "F" and identificador == ident:
        print(linha)

and I’m using this data saved in . csv to read:

C;1;Kenneth;[email protected]
F;1;Matrix;5.0
F;1;Mad Max;4.5
C;2;Josue;[email protected]
F;2;Miss Sunshine;4.2
C;3;Maria;[email protected]
F;3;Amelie Poulain;3.0
F;3;Drive;2.0

What to do to delete a critic’s lines?

EDIT: Small error while deleting files. inserir a descrição da imagem aqui

  • Question: if you search for the name of the critic, it would not be enough for you to compare critico == nome instead of doing critico in linha? And when located the critical, is stored in ident the value of identificador and all lines with this identifier shall be removed?

  • Yes, seeing here you are correct, is that I knew about this method of putting variables for each column now. When the critic is located all lines with this identifier should be removed, then yes.

2 answers

2

Read the file to a list, like this:

with open('csv1.csv', 'r') as f:
   linhas = csv.reader(f, delimiter=';')
   lst = list(linhas) 

From a print in the list to see its contents:

print (lst)

Then remove the element you want through its value, something like:

 lst.remove([F,1,Matrix,5.0])

Save the list (without the removed ones) by overwriting the original file:

with open('csv1.csv', 'w') as f: 
    writer = csv.writer(f)
    writer.writer(lst)

2


To avoid the need to work with temporary files, you should store the entire contents of the file in memory and write it as needed. To do this, we read the entire file:

# Abre o arquivo para a leitura:
with open("data.csv", "r") as file:

    # Analisa o arquivo como CSV:
    reader = csv.reader(file, delimiter=';')

    # Armazena o conteúdo do arquivo em memória:
    data = list(reader)

Thus the object data will be a list of all lines of the file. For writing then we open the file in the mode w and travel the lines in data, checking:

# Abre o arquivo para escrita:
with open("data.csv", "w") as file:

    # Cria o objeto de escrita CSV:
    writer = csv.writer(file, delimiter=';', lineterminator='\n')

    # Identificador do crítico:
    ident = None

    # Percorre as linhas do arquivo:
    for line in data:

        # Extrai os dados da linha:
        tipo, identificador, nome, nota = line

        # Verifica se a linha corresponde ao crítico:
        if tipo == 'C' and nome == critico:

            # Sim, então define o identificador:
            ident = identificador

        # Verifica se a linha não é uma avaliação do crítico:
        if identificador != ident:

            # Sim, então mantém a linha no arquivo:
            writer.writerow(line)

See working on Repl.it.

  • It worked, but when I run on Pycharm or Atom the csv file after running the code it gets a blank space between the lines, thus making it "not enough values" error. Ex: I delete Kenneth and all movies related to him, after deleted the file puts a blank space on each line. Is there any method to print without these blanks? OBS: Image of the file updated above.

  • @Kennethanderson tidy up.

  • With a newline=" " when opening the file also works, I just tested.

Browser other questions tagged

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