1

I am trying to delete the row being used in my csv file but I am unsure how to approach it. I want to delete the first row that is used in the file (not including the header. I also want to use the same file, not create a new one. Here is what I have so far:

if os.path.isfile('test.csv'):
    with open("test.csv", "r") as f_input:
        csv_input = csv.reader(f_input)
        next(f_input) #skips header
        for row in csv_input:
            item_c =row[0]
            item_l = row[1]
            item_v = row[2]
            item_k = row[3]
            #DELETE THE ROW AFTER I GET THE INFO FOR EACH "item"
John
  • 35
  • 4
  • you will probably need a writer for that which will work with file header in write mode.https://stackoverflow.com/questions/29725932/deleting-rows-with-python-in-a-csv-file – mad_ Aug 08 '18 at 17:05
  • may be you can keep one more list and append it with the rows you wish to keep then write those rows into the file. – mad_ Aug 08 '18 at 17:07
  • Do you want delete only one specific row based on some condition? Is the file big or small? – CodeSamurai777 Aug 08 '18 at 17:11
  • @mrangry777 I want to delete the first row that is used in the file (not including the header) – John Aug 08 '18 at 17:27
  • 1
    @John Edited my answer too include solution for deleting rows with specific indexes the `n_list` holds those indexes – CodeSamurai777 Aug 08 '18 at 17:32

1 Answers1

1

You could recreate the input file with the specific rows deleted and then delete the original file. You could also do it by reading the whole file into memory next deleting some rows and recreating it. However, the second approach is much riskier. Here is how it could go:

import csv
if os.path.isfile('test.csv'):
   with open('test.csv', 'r') as inp, open('test_edited.csv', 'w') as out:
      writer = csv.writer(out)
      reader = csv.reader(inp)
      writer.writerow(next(reader)) #copy headers
      for row in reader:
            item_c = row[0]
            item_l = row[1]
            item_v = row[2]
            item_k = row[3]
            if item_k != "someValue":  #Here you put any condition you want
               writer.writerow(row)    #Save only the rows that do not have someValue

At the end you could delete the orginal file

Deleting rows with specific indexes:

import csv
n_list = [1]
if os.path.isfile('test.csv'):
   with open('test.csv', 'r') as inp, open('test_edited.csv', 'w') as out:
      writer = csv.writer(out)
      reader = csv.reader(inp)
      writer.writerow(next(reader)) #copy headers
      index = 1
      for row in reader:
            item_c = row[0]
            item_l = row[1]
            item_v = row[2]
            item_k = row[3]
            if index not in n_list:  #Here you put any condition you want
               writer.writerow(row)    #Save only the rows that do not have someValue
            index+=1
CodeSamurai777
  • 3,285
  • 2
  • 24
  • 42