First, why this fails:
You use to not provoke backtracking, which may be a good technique, but does not exist. Because it will make your predicate false at the end when the member has run out of decisions. Then, as soon as the loop_through_list is false, it is said that it has not been reached and the recording has not been performed properly (when I test it, the file is created, but nothing is written).
If you use:
loop_through_list([]). loop_through_list([Head|Tail]) :- write(Head), write(' '), loop_through_list(Tail).
instead it works.
But even if this code works, you can use open (file name, record, stream), write (stream, element) and close (stream), and do not tell and explain the reasons explained in the link at the bottom of this answer. For instance:
loop_through_list(_File, []) :- !. loop_through_list(File, [Head|Tail]) :- write(File, Head), write(File, ' '), loop_through_list(File, Tail). write_list_to_file(Filename,List) :- open(Filename, write, File), loop_through_list(File, List), close(File).
or
loop_through_list(File, List) :- member(Element, List), write(File, Element), write(File, ' '), fail. write_list_to_file(Filename,List) :- open(Filename, write, File), \+ loop_through_list(File, List), close(File).
using your code and the joel76 trick.
See Prolog to save a file in an existing file.
It covers the same issue.