writing to a csv file

443 views
Skip to first unread message

sarah fekih

unread,
May 9, 2020, 9:38:40 AM5/9/20
to netlogo-users
Hi
I have created a neighbor network for 1000 (households ) agents : 

to Neighbor-network
 
  ask n-of 1000 households 
  [ create-links-with min-n-of 7 other households [distance myself]
  ]
  
 
  ask one-of households with [count link-neighbors > 1]
  [
      ask link-neighbors [print who]] 
end 

I want to write in a csv file where it shows "yes "in front of every households who got a link with a neighbor and  a "no" for the ones that didn't got one
so far i managed to write the turtle id in my csv  using "who":

 if (file-exists? "output/attribute.csv")
  [
    carefully
    [file-delete "output/attribute.csv"]
    [print error-message]
  ]
  file-open "output/attribute.csv" 
  foreach sort households [aturtle -> ask aturtle [
  file-write who file-type ","  file-type "\n"]]
  file-close

Thank you !  

Charles Staelin

unread,
May 9, 2020, 4:24:30 PM5/9/20
to netlogo-users
Hi Sarah,

The easiest way to write a CSV file is with the CSV extension. The extension takes a list of lists, where each sublist is a line of the file to be written.  You would load the extension by putting the line 
extensions [CSV]

at the beginning of you model - before your breed definitions, etc.  The file-writing code would then be 
file-open "output/attribute.csv"
  let
out-list []

 
foreach sort households [aturtle ->
    ask aturtle
[

     
set out-list lput (list who ifelse-value (any? link-neighbors) ["true"] ["false"]) out-list
   
]
 
]
  csv
:to-file "output/attribute.csv" out-list
  file
-close

Each household creates a list of its who number and either "true" or "false", depending on whether it has any link-neighbors.  It then appends that list to out-list, giving you a list of lists.  The line 
csv:to-file "output/attribute.csv" out-list

then writes that list to your file, one sublist to a line.  The CSV extension is really handy for reading and writing CSV files.  You will use it often.  And creating lists for your output lines makes it easy to add or modify the variables you want to write, without having to worry about inserting commas and line feeds.

Hope this helps,
Charles
Reply all
Reply to author
Forward
0 new messages