Delete a particular row from a .csv using Python

0

What I would like to do is that when the user types the name of a person who was inside the .csv file, his line and the lines of movies that he evaluated were deleted (I used an identifier for that), 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 do I do to delete the lines of a critic?

EDIT: Small error deleting files.

    
asked by anonymous 09.08.2017 / 23:29

2 answers

1

To avoid the need to work with temporary files, you must store all the contents of the archive 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 data object will be a list with all rows in the file. For writing, then we open the file in w mode and we go through the lines in data by 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 at Repl.it .

    
10.08.2017 / 00:23
1

Read the file for 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)
    
10.08.2017 / 00:17