Jack
Jack

Reputation: 1437

Netlogo - read and import string data from txt file

I am trying to read a .txt file containing strings:

Delivery    LHR    2018
Delivery    LHR    2016
Delivery    LHR    2014
Delivery    LHR    2011
Delivery    LHR    2019
Delivery    LHR    1998

I have tried below codes but not working. It reported "expect a literal value" when running file-read

globals [input]

to setup
  set input []
  file-open "test.txt"
  while [not file-at-end?]
  [
    let a quote file-read
    let b quote file-read

    set input lput a input
    set input lput b input
    print input
  ]
  file-close
end

 to-report quote [ #thing ]
 ifelse is-number? #thing
 [ report #thing ]
 [ report (word "\"" #thing "\"") ]
 end

Upvotes: 2

Views: 1067

Answers (2)

Jasper
Jasper

Reputation: 2790

You can kind-of get what you want with the csv extension which comes with NetLogo. It at least let's you specify a delimiter, so " ", but you'll have to manually read past all the blank columns it'll see.

extensions [csv]

globals [input]

to setup
  set input []
  let lines (csv:from-file "test.txt" " ")
  foreach lines [ line ->
    let col1 (item 0 line)
    let i 1
    while [item i line = ""] [ set i (i + 1) ]
    let col2 (item i line)
    show col2
    set i (i + 1)
    while [item i line = ""] [ set i (i + 1) ]
    let col3 (item i line)
    show col3
    set input lput col1 input
  ]
  show input
end

Upvotes: 3

nldoc
nldoc

Reputation: 1209

The reason it doesn`t work can be found in the file-read description from the NetLogo Dictionary Manual (https://ccl.northwestern.edu/netlogo/docs/dictionary.html#file-read)

[...]Note that strings need to have quotes around them.[...]

It is not a solution to add the quotes within NetLogo because file-read already throws an Error, if the next entry in the file is not one of number, list, string, boolean, or the special value nobody. And string in this case means, it needs to have quotes around it.

Thus, to read the file into NetLogo you have to put quotes around the strings in your input file. Alternatively, if the strings in your input file always have the same length, you could try to read the file using the primitive file-read-characters. Here is an example that should work with your input file:

to setup
  file-open "test.txt"
  while [not file-at-end?]
  [
    let a file-read-characters 8
    let skip file-read-characters 4
    let b file-read-characters 3
    let c file-read

    print (list a b c)
  ]
  file-close
end

Upvotes: 2

Related Questions