James Bassett - 2013-01-19

I received an email with the following question:

How do I add columns to an existing csv file? The idea is to write time series data out to a csv file. Every time step I would like to add a new column to the existing csv
file.

Right now I am using a CsvMapWriter to write the original csv file.

I found "CsvContext" which let's me set column number but I don't know how to actually use in the context I need it in.

You can't edit the existing file, but you can write a new file with the new column added. There's a similar question on the forum - it's deleting whole lines instead of adding a column - but you can see how you can combine the reader and writer to achieve this.

Here's a simple example...

Original CSV:

userid,name
1,Jim
2,Sally
3,Bob

Java:

package example;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

import org.supercsv.io.CsvMapReader;
import org.supercsv.io.CsvMapWriter;
import org.supercsv.io.ICsvMapReader;
import org.supercsv.io.ICsvMapWriter;
import org.supercsv.prefs.CsvPreference;

public class Example {

    public static void main(String[] args) throws IOException {

        ICsvMapReader mapReader = null;
        ICsvMapWriter mapWriter = null;
        try {
            CsvPreference prefs = CsvPreference.STANDARD_PREFERENCE;
            mapReader = new CsvMapReader(new FileReader("input.csv"), prefs);
            mapWriter = new CsvMapWriter(new FileWriter("output.csv"), prefs);

            // header used to read the original file
            final String[] readHeader = mapReader.getHeader(true);

            // header used to write the new file 
            // (same as 'readHeader', but with additional column)
            final String[] writeHeader = new String[readHeader.length + 1];
            System.arraycopy(readHeader, 0, writeHeader, 0, readHeader.length);
            final String timeHeader = "time";
            writeHeader[writeHeader.length - 1] = timeHeader;

            mapWriter.writeHeader(writeHeader);

            Map<String, String> row;
            while( (row = mapReader.read(readHeader)) != null ) {

                // add your column with desired value
                row.put(timeHeader, String.valueOf(System.nanoTime()));

                mapWriter.write(row, writeHeader);
            }

        }
        finally {
            if( mapReader != null ) {
                mapReader.close();
            }
            if( mapWriter != null ) {
                mapWriter.close();
            }
        }

    }

}

New CSV:

userid,name,time
1,Jim,64913824823208
2,Sally,64913824900056
3,Bob,64913824966956
 

Last edit: James Bassett 2013-01-19