Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
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()
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.
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 questionAsk a Question
731 491 924 answers to any question