文件打印似乎不起作用

时间:2015-03-23 20:36:31

标签: netlogo

breed[inboxturtles inboxturtle]
to check
  create-inboxturtles 100[setxy random-xcor random-ycor] 
  file-open "D:\\hello.csv"
  file-write "X Coordinate" file-write "," file-write "Y Coordinate" file-write "," 
  file-write "Who" file-print ""
      ask inboxturtles [ 
        file-print ""
        file-write xcor file-write ","
        file-write ycor file-write ","
        file-write who 
        ]  
  file-close
  end

我不知道file-print无法在ask中工作,但它肯定在它之外工作。有人可以帮助我吗,我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

对我来说很好:

 "X Coordinate" "," "Y Coordinate" "," "Who"

 -11.273903984790302 "," 11.589865065737627 "," 60
 -3.198704310517442 "," -2.327808927515365 "," 6
 13.485197306065764 "," -3.747989432973762 "," 91
 16.085782333733263 "," 13.530031781112555 "," 35
 ...

顺便说一句,您应该使用file-type代替file-write来写入文件而不附加换行符。

file-write做了奇怪的事情,比如在所有字符串周围加上引号(这就是为什么逗号在上面的输出中是引号)。

更好的是,您应该使用word反复连接字符串而不是file-write(或file-type)。我会这样编写上面的代码:

to check
  create-inboxturtles 100[setxy random-xcor random-ycor] 
  file-open "D:\\hello.csv"
  file-print "X Coordinate,Y Coordinate,Who"
  ask inboxturtles [
    file-print (word xcor "," ycor "," who) 
  ]  
  file-close
end

输出:

X Coordinate,Y Coordinate,Who
-5.409837709344972,-0.6301891295194455,165
15.024747417946124,-9.591123025568086,193
9.735972095912903,-3.935540025692582,176
-11.505336629875304,-12.082889705829679,103
-10.19902536584426,-14.86360155896942,85
-5.928287603043071,7.175770417278386,22
-10.538908046584938,-15.009427435006804,120
...

这可能更符合您的要求。顺便说一句,在CSV中,可以在字符串中包含空格而不在它们周围添加引号。您需要引号的唯一时间是字符串本身包含逗号。

最后请注意,如果文件已存在,则只会附加而不是覆盖。因此,在if file-exists? filename [ file-delete filename ]之前,您可能需要file-open之类的内容。

答案 1 :(得分:2)

请改用file-type。如果你真的想要字符串的引号,你可以添加它们。

breed[inboxturtles inboxturtle]

to check
  file-open "c:/temp/temp.csv"
  file-type xcor 
  file-type "," file-type ycor 
  file-type "," file-type who 
  file-print ""
  file-close
end

to setup
  ca
  carefully [file-delete "C:/temp/temp.csv"] []
  file-open "C:/temp/temp.csv"
  file-type "\"X Coordinate\"" 
  file-type "," file-type "\"Y Coordinate\"" 
  file-type "," 
  file-type "\"Who\"" 
  file-print ""
  file-close
  create-inboxturtles 100[setxy random-xcor random-ycor] 
end

to go
  ask inboxturtles [check]
end