Unable to delete rows from the .csv pyexcel file

advertisements

Here is my function:

     def prepare_file(time, mkt):
        # renames file to corresponding market name
        global previous_time
        for file in glob.glob(os.getcwd()+'\Reports\*'):
            # if it's the most recently downloaded file
            if time > previous_time:
                previous_time = time
                # remove rows for properties that have not changed status
                sheet = pyexcel.get_sheet(file_name=file)
                for row in sheet:
                    if row[1] in changed_addresses:
                        pass
                    else:
                        del row
                # save file as correct name
                sheet.save_as(
                    os.getcwd() + '\\Reports\\' + mkt[0] + '.csv'
                )
                os.remove(file)

The idea is to find the most recently downloaded file in a directory, open it, remove all rows that do not contain a address from the changed_addresses list, and save it as a string contained in the mkt list.

Everything works fine except for the deletion of the rows. It iterates through them correctly, and understands when a row should be deleted, but the outputted file still contains all the rows that should be gone.

is del row not the correct command for this case?


Using csv I think this should work:

import csv
import os
import glob

def prepare_file(time, mkt):
   # renames file to corresponding market name
   global previous_time
   for file in glob.glob(os.getcwd()+'\Reports\*'):
       # if it's the most recently downloaded file
       if time > previous_time:
           previous_time = time
           # remove rows for properties that have not changed status
           fin = open(file, 'r')
           fout = open((os.getcwd() + '\\Reports\\' + mkt[0] + '.csv'), 'w', newline='')
           reader = csv.reader(fin)
           writer = csv.writer(fout)

           for row in reader:
               if row[1] not in changed_addresses:
                   writer.writerow(row)

           # close files
           fin.close()
           fout.close()

           # remove original
           os.remove(file)

So first opening your datafile with name file, and later saving it with the new name.