Reputation: 330
I built a model in Prolog, which generates dynamic results when I do requiring through compiler. I wanna output the dynamic results as csv from swi-prolog. But because it's dynamic and each moment the columns and rows numbers are changing.
My question is is there anyway I can rewrite the output csv file (cover the old one)? Otherwise how can I output the results when columns and rows are keep changing?
Upvotes: 1
Views: 266
Reputation: 4797
As Lurker said I think you just want to make sure the output mode of open/3
is set to write
. I have the following which I think does what want you want. You can adapt the header row and the first column to have special properties if you desire. Adapted from(DCG for file output).
csvfile(Headers,Rows) -->
headerrow(Headers),
normalrows(Rows).
headerrow([]) --> [newline].
headerrow([X]) -->atom(X),[newline].
headerrow([X,Y|Rest]) --> atom(X),atom(', '), headerrow([Y|Rest]).
normalrows([])-->[newline].
normalrows([X|Rest]) --> row(X),normalrows(Rest).
row([H|Rest]) -->
firstitem(H),
restitems(Rest).
firstitem(H)--> atom(H),atom(', ').
restitems([]) --> [newline].
restitems([X]) -->atom(X),[newline].
restitems([X,Y|Rest]) --> atom(X),atom(', '), restitems([Y|Rest]).
atom(A) -->[atom(A)].
output(Stream,newline) :-nl(Stream).
output(Stream,atom(A)):- format(Stream,"~w",[A]).
csvfile_header_rows(File,Header,Rows):-
phrase(csvfile(Header,Rows),Ts),
setup_call_cleanup(
open(File,write,Stream),
maplist(output(Stream),Ts),
close(Stream)
).
Example:
?-csvfile_header_rows('csv_test.csv',[name,age,sex],[[bob,20,m],[wilma,23,f],[bert,34,m]]).
Upvotes: 3