5

I am appending the data to the last row of a csv. I wanted to delete the existing row and then rewrite it with the appended element. Is there any way of deleting the row in csv? I am using opencsv to read and the write the file. I tried using CSVIterator class. However, it seems the iterator does not support the remove() operation. Here is the code that I tried:

static String[] readLastRecord(File outputCSVFile) throws WAGException {
        checkArgument(outputCSVFile != null, "Output CSV file cannot be null");
        FileReader fileReader = null;
        CSVReader csvFileReader = null;
        CSVIterator csvIterator = null;
        String[] csvLastRecord = null;
        try {
            fileReader = new FileReader(outputCSVFile);
            csvFileReader = new CSVReader(fileReader, ',', '\'',
                    csvRowCount - 1);
            csvIterator = new CSVIterator(csvFileReader);
            while (csvIterator.hasNext()) {
                csvLastRecord = csvIterator.next();
                csvIterator.remove();
            }
        } catch (IOException ioEx) {
            throw new WAGException(
                    WAGInputExceptionMessage.FILE_READ_ERR.getMessage());
        } finally {
            try {
                if (csvFileReader != null)
                    csvFileReader.close();
            } catch (IOException ioEx) {
                throw new WAGException(
                        WAGInputExceptionMessage.FILE_CLOSE_ERR.getMessage());
            }
        }
        return csvLastRecord;
    }
user3453784
  • 593
  • 3
  • 9
  • 19
  • The API says that `remove()` *is* supported by iterator: http://opencsv.sourceforge.net/apidocs/ when you write "it seems the iterator does not support the remove() operation" - you should provide more details: it doesn't compile ? it compiles but doesn't run ? it runs but doesn't do what you want it to do ? – Nir Alfasi Nov 24 '14 at 04:54
  • The implementation on the sourceforge.net says its not supported.. It is a read-only iterator. http://sourceforge.net/p/opencsv/source/ci/3ba1873ef55b014893cae73b015d2bcb55b7d5a4/tree/src/main/java/au/com/bytecode/opencsv/CSVIterator.java – user3453784 Nov 24 '14 at 04:59
  • In that case - you'll have to read all the lines into a data-structure (List might be good enough), remove the line you want and override (re-write) the file. – Nir Alfasi Nov 24 '14 at 05:01

2 Answers2

7

i just found an answer. Hope it helps.

You need to read the csv, add elements to the list string, remove specific row from it with allelements.remove(rowNumber) and then write the list string back to the csv file.

The rowNumber is an int with row number.

CSVReader reader2 = new CSVReader(new FileReader(filelocation));
List<String[]> allElements = reader2.readAll();
allElements.remove(rowNumber);
FileWriter sw = new FileWriter(filelocation);
CSVWriter writer = new CSVWriter(sw);
writer.writeAll(allElements);
writer.close();

Look at this example from opencsv opencsv example

teamyates
  • 414
  • 1
  • 7
  • 25
Wladislaw
  • 1,200
  • 2
  • 12
  • 23
0

use unset to remove the row in csv

function readCSV($csvFile){
   $file_handle = fopen($csvFile, 'r');
   while (!feof($file_handle) ) {
      $line_of_text[] = fgetcsv($file_handle, 1024);
   }
   fclose($file_handle);
   return $line_of_text;
}

$csvFile1 = '../build/js/snowcem.csv';
$csv1 = readCSV($csvFile1); 
//specified row number want to delete on place of $id
unset($csv1[$id]);
$file = fopen("../build/js/snowcem.csv","w");

foreach ($csv1 as $file1) {
    $result = [];
    array_walk_recursive($file1, function($item) use (&$result) {
    $item = '"'.$item.'"';
        $result[] = $item;
    });
    fputcsv($file, $result);
}

fclose($file);