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:
packageexample;importjava.io.FileReader;importjava.io.FileWriter;importjava.io.IOException;importjava.util.Map;importorg.supercsv.io.CsvMapReader;importorg.supercsv.io.CsvMapWriter;importorg.supercsv.io.ICsvMapReader;importorg.supercsv.io.ICsvMapWriter;importorg.supercsv.prefs.CsvPreference;publicclassExample{publicstaticvoidmain(String[]args)throwsIOException{ICsvMapReadermapReader=null;ICsvMapWritermapWriter=null;try{CsvPreferenceprefs=CsvPreference.STANDARD_PREFERENCE;mapReader=newCsvMapReader(newFileReader("input.csv"),prefs);mapWriter=newCsvMapWriter(newFileWriter("output.csv"),prefs);// header used to read the original filefinalString[]readHeader=mapReader.getHeader(true);// header used to write the new file // (same as 'readHeader', but with additional column)finalString[]writeHeader=newString[readHeader.length+1];System.arraycopy(readHeader,0,writeHeader,0,readHeader.length);finalStringtimeHeader="time";writeHeader[writeHeader.length-1]=timeHeader;mapWriter.writeHeader(writeHeader);Map<String,String>row;while((row=mapReader.read(readHeader))!=null){// add your column with desired valuerow.put(timeHeader,String.valueOf(System.nanoTime()));mapWriter.write(row,writeHeader);}}finally{if(mapReader!=null){mapReader.close();}if(mapWriter!=null){mapWriter.close();}}}}
I received an email with the following question:
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:
Java:
New CSV:
Last edit: James Bassett 2013-01-19