I
I
Ivan Yakushenko2019-05-01 12:25:17
Python
Ivan Yakushenko, 2019-05-01 12:25:17

How to find a row in CSV and delete it?

I have a CSV file with the following structure:

Ivan,test
000000000,Ivan,test test test
000000000,Ivan,column 000000000, Ivan
,bla bla bla 000000000
,Ivan,oops

I need to find a line with a value, for example "oops", then copy the value of this line into a variable, and delete the line itself from CSV. How can I do that?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry, 2019-05-01
@kshnkvn

from typing import List, Tuple
import csv

SOURCE_CSV = 'source.csv'
SUBSTR = 'ooops'
COL_WITH_VALUES = 1


def main():
    data = get_data_from_file(SOURCE_CSV)
    filtered_data, clone_rows = data_filter(data, SUBSTR, COL_WITH_VALUES)
    save_data(SOURCE_CSV, filtered_data)


def save_data(file_path: str, rows: List[List[str]]):
    with open(file_path, 'w', newline='') as f:
        w = csv.writer(f)
        w.writerows(rows)


def data_filter(rows: List[List[str]], subst: str, col: int) -> Tuple[List[List[str]], List[List[str]]]:
    filtered_data = []
    clone_rows = []
    for row in data:
        if row[col] == subst:
            rows_with_subst.append(row)
        else:
            filtered_data.append(row)
    return filtered_data, clone_rows


def get_data_from_file(file_path: str) -> List[List[str]]:
    with open(SOURCE_CSV, 'r') as f:
        data = [x for x in csv.reader(f)]
    return data


if __name__ == "__main__":
    main()

D
Developer, 2019-05-01
@samodum

You read csv line by line and copy everything to the second file. Thus you do check with your condition.
After that, you delete the original file, and rename the new one to the old one.

V
Vadim Shatalov, 2019-05-01
@netpastor

It is easier, faster and more correct to load into pandas, make the necessary selection and upload to csv

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question