How can I write data to CSV file from the prolog code below?
Thanks,
SB
run:-
member(A,[a,b,c,d,e]),
member(B,[1,2,3,4,5,6]),
write(A),write(' '),write(B),nl,
fail.
run.
How can I write data to CSV file from the prolog code below?
Thanks,
SB
run:-
member(A,[a,b,c,d,e]),
member(B,[1,2,3,4,5,6]),
write(A),write(' '),write(B),nl,
fail.
run.
Since you are using SWI-Prolog, you can use the CSV library.
?- use_module(library(csv)).
?- findall(row(A,B), (member(A, [a,b,c,d,e]), member(B, [1,2,3,4,5])), Rows), csv_write_file('output.csv', Rows).
As you can see, I do this in two steps:
row(A, B)
.csv_write_file/2
which takes care of creating a syntactically correct output file.In your question you are not writing a comma between A
and B
but a space. If you really want to use the space as a separator you can set this as an option:
csv_write_file('output.csv', Rows, [option(separator(0' )])
Also, in your question you have more values for B
than for A
. You can write code that handles this, but there are several ways in which this can be dealt with. E.g., (1) you can fill missing cells with nill
; (2) you can throw an exception if same_length(As, Bs)
fails; (3) you can only write the 'full' rows:
length(As0, N1),
length(Bs0, N2),
N is max(N1, N2),
length(As, N),
append(As, _, As0),
length(Bs, N),
append(Bs, _, Bs0),