How to read a .CSV file with netlogo?

前端 未结 2 1144
故里飘歌
故里飘歌 2021-01-20 01:40

I\'m starting in netlogo these days, so I\'ve got some problems that I didn\'t find how to solve them. I have to read a huge .csv file, got this code on the web:

2条回答
  •  一个人的身影
    2021-01-20 02:03

    The code seems basically correct. I assume that csv and fileList are defined as global variables, otherwise the "set" commands on each will generate compile-time errors. We can also delete the reference to fileList in the while block since it is reset anyway once the while loop exits. Then, if you want to keep the semicolon as the separator we can make that change as well. Altogether, we get:

    globals [csv fileList]
    
    to openFile
    file-open "testeCsv.csv"
    set csv file-read-line
    set csv word csv ";"  ; add semicolon for loop termination 
    
    let mylist []  ; list of values 
      while [not empty? csv] 
      [
        let $x position ";" csv 
        let $item substring csv 0 $x  ; extract item 
        carefully [set $item read-from-string $item][] ; convert if number 
        set mylist lput $item mylist  ; append to list 
        set csv substring csv ($x + 1) length csv  ; remove item and comma 
      ] 
      set fileList mylist
      show fileList
    end
    

    When I run this on the line in the CSV file you provide (after converting the decimal separator in the file from "," to ".") I get the result you seek, [1 0 0 65 0 2 45 0 -0.018961934].

    Of course that reads only one line in the file. I assume that you will want to loop through each line in the file, storing or using each line as it is read. The following stores each line in a list of lists.

    globals[csv fileList]
    
    to openFile
      file-open "testeCsv.csv"
      set fileList []
    
      while [not file-at-end?] [
        set csv file-read-line
        set csv word csv ";"  ; add comma for loop termination 
    
        let mylist []  ; list of values 
        while [not empty? csv] 
        [
          let $x position ";" csv 
          let $item substring csv 0 $x  ; extract item 
          carefully [set $item read-from-string $item][] ; convert if number 
          set mylist lput $item mylist  ; append to list 
          set csv substring csv ($x + 1) length csv  ; remove item and comma 
        ] 
        set fileList lput mylist fileList
      ]
    
      show fileList
      file-close
    end
    

提交回复
热议问题