Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search Delete using csv.reader in python

Tags:

python

csv

I want to search a column and delete from csv file using python. I cannot dataframes as I need to work with large files and can't load it in RAM. How to do it? example csv file-

Home,Contact,Adress
abc,123,xyz 

I need to find and delete Contact for example. I thought to use csv.reader but cannot figure out how to do it

like image 819
devesh marwah Avatar asked Jun 27 '26 14:06

devesh marwah


1 Answers

Check this :

import csv

col = 'Contact'

with open('your_csv.csv') as f:
    with open('new_csv.csv', 'w', newline='') as g:
        
        # creating csv reader
        reader = csv.reader(f)

        # getting the 'col' index in the header, we want to delete it in the next lines
        col_index = next(reader).index(col)

        for line in reader:
            del line[col_index]

            # writing to new csv file
            writer = csv.writer(g)
            writer.writerow(line)

Explanation for using newline='' is here.

like image 87
SorousH Bakhtiary Avatar answered Jun 29 '26 03:06

SorousH Bakhtiary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!