Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I append text to a csv/txt file in Processing?

I use this simple code to write a few strings to the file called "example.csv", but each time I run the program, it overwrites the existing data in the file. Is there any way to append the text to it?

void setup(){
  PrintWriter output = createWriter ("example.csv");
  output.println("a;b;c;this;that ");
  output.flush();
  output.close();

}
like image 597
Faridoon Avatar asked Jun 09 '13 13:06

Faridoon


People also ask

Which function is used to append text to a text file?

The WriteAllText method can be used to append to a text file by specifying that the append parameter is set to True .

How do you write text in a csv file?

Go to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited).

How do you append data to a file?

If you are working on text data and the number of write operations is less, use FileWriter and use its constructor with append flag value as true . If the number of write operations is huge, you should use the BufferedWriter. To append binary or raw stream data to an existing file, you should use FileOutputStream.


1 Answers

import java.io.BufferedWriter;
import java.io.FileWriter;

String outFilename = "out.txt";

void setup(){
  // Write some text to the file
  for(int i=0; i<10; i++){
    appendTextToFile(outFilename, "Text " + i);
  } 
}

/**
 * Appends text to the end of a text file located in the data directory, 
 * creates the file if it does not exist.
 * Can be used for big files with lots of rows, 
 * existing lines will not be rewritten
 */
void appendTextToFile(String filename, String text){
  File f = new File(dataPath(filename));
  if(!f.exists()){
    createFile(f);
  }
  try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f, true)));
    out.println(text);
    out.close();
  }catch (IOException e){
      e.printStackTrace();
  }
}

/**
 * Creates a new file including all subfolders
 */
void createFile(File f){
  File parentDir = f.getParentFile();
  try{
    parentDir.mkdirs(); 
    f.createNewFile();
  }catch(Exception e){
    e.printStackTrace();
  }
}    
like image 180
Pwdr Avatar answered Sep 20 '22 06:09

Pwdr