Rizwan606
Rizwan606

Reputation: 667

Clearing File Data before writing in Netlogo

I am trying to output some data in a file and I can output the data in file easily. But when I output data second time in file, it gets appended with the previous data. What I want to do is to clear the previous data and insert only the new data without appending the new data with old data. Below is my code :

     file-open "savedgame.txt"

       foreach sort turtles [
    ask ? [
      file-print (turtlenumbers) // ; This appends the "turtlenumbers" with old data in
                                 //  ;  file (if any). I want to clear file before 
                                 //  ;writing "turtlenumbers" in the file


       file-print ""

    ]
  ] 
   file-close

Upvotes: 1

Views: 438

Answers (1)

Nicolas Payette
Nicolas Payette

Reputation: 14972

As per the file-open documentation in the NetLogo dictionnary:

When opening a file in writing mode, all new data will be appended to the end of the original file. If there is no original file, a new blank file will be created in its place. (You must have write permission in the file's directory.) (If you don't want to append, but want to replace the file's existing contents, use file-delete to delete it first, perhaps inside a carefully if you're not sure whether it already exists.)

In other words, add this as your very first line:

carefully [ file-delete "savedgame.txt" ] [ ]

Upvotes: 2

Related Questions