0

I want to Remove a row from my csv file but after using remove method, the whole file is getting empty. What changes should i do to remove row according to college id ?

import csv

class College:

    def addclg(self):
        with open('colleges.csv', 'a', newline='') as fp:
            a=csv.writer(fp)
            id = input("Enter College ID:")
            name = input("Enter College Name:")
            course = input("Enter Course:")
            city = input("Enter your City:")
            fees = input("Enter your Fess:")
            pin = input("Enter your Pincode:")
            a.writerow([id, name, course, city, fees, pin])
            fp.close()

    def display(self):
        with open('colleges.csv', 'r') as fp:
            a=csv.reader(fp)
            for row in a:
                if row[3]=='Mumbai' and row[2]=='Engineering' :
                    print (row)
        fp.close()

    def remove(self):
        data=list()
        with open('colleges.csv', 'r') as fp2:
            a2=csv.reader(fp2)
            for row2 in a2:
                print (row2[0],row2[1])
            id = input("Enter College ID you want to delete:")
            for row2 in a2:
                data.append(row2)
                for field in row2:
                    if field == id:
                        data.remove(row2)
        with open('colleges.csv', 'w') as fp:
            a=csv.writer(fp)
            a.writerow(data)
        fp.close()
        fp2.close()

ch=input('a. Register New College\nb. Display colleges in Mumbai who teach Engineering\nc. Remove College Based on collegeid\nEnter your Choice: ')
obj1=College()
if (ch=='a'):
    obj1.addclg()
elif(ch=='b'):
    obj1.display()
elif(ch=='c'):
    obj1.remove()
else:
    print('Wrong Choice')

data of csv file: 111,K.J.Somaiya College,Engineering,Mumbai,10000,400077 222,Dr. Vasantrao Pawar College,Medical,Nashik,20000,422207

David Specht
  • 7,784
  • 1
  • 22
  • 30
Mehul Patel
  • 1
  • 1
  • 6
  • can you also add few rows of the csv file? – jen Aug 06 '20 at 14:29
  • Hi Mehul, welcome to Stackoverflow. As Jen says, some data for us to work on would be helpful. Off the top of my head, I’m suspicious of the last line: you are giving a.writerow a list of lists of strings, but I think it wants a single list of strings. Perhaps you should loop through data feeding it one list at a time? – Tim Aug 06 '20 at 14:58

2 Answers2

0

your logic seems ok, but there's a 'trick' in the csv.reader() method.

Its a special method called a generator, and its elements can only be called once.

So we could run a2=csv.reader(fp2) a second time after the first loop right?

But fp2 is also a generator! So you won't get anything either.

The easiest is to keep your result set in a variable, make use of data on the first iteration:

def remove(self):

    data=list()

    with open('colleges.csv1', 'r') as fp2:

        a2=csv.reader(fp2)

        for row2 in a2:
            data.append(row2) # Filling up data as we print it
            print (row2[0],row2[1])

   id = input("Enter College ID you want to delete:")
   
   # Than just iterate over data
   for row in data:
       for field in row:
           if field == id:
              data.remove(row2)

   with open('colleges.csv', 'w') as fp:
       a=csv.writer(fp)
       a.writerow(data)
Bastien Harkins
  • 295
  • 1
  • 7
0

Why you don't use pandas here? I'm assuming that your csv has a column called 'College ID' here.

import pandas as pd
df = pd.read_csv('colleges.csv')
id = input("Enter College ID you want to delete:")

df = df[df["College ID"]!=id].reset_index(drop=True)
df.to_csv("colleges_filtered.csv", index=False)
rpanai
  • 12,515
  • 2
  • 42
  • 64