# Saving prolog query results in Python

**URL:** <https://swi-prolog.discourse.group/t/saving-prolog-query-results-in-python/6628>\
**Category:** Algorithm\
**Tags:** how-to\
**Created:** [June 11, 2023, 12:35pm UTC](https://swi-prolog.discourse.group/t/saving-prolog-query-results-in-python/6628 "2023-06-11T12:35:32Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![srydn](https://avatars.discourse-cdn.com/v4/letter/s/f9ae1b/32.png) [@srydn](https://swi-prolog.discourse.group/u/srydn)\
**Post date:** [June 11, 2023, 12:35pm UTC](https://swi-prolog.discourse.group/t/saving-prolog-query-results-in-python/6628/1 "2023-06-11T12:35:32Z")

</div>

Hello,

I am trying to save the prolog.query() results to a file in Python. I tried so many things but I could not find a solution for that. I would be so glad if anyone can help me with this.  
 ![prologForumSoru](https://global.discourse-cdn.com/free1/uploads/swiprolog/original/2X/9/93b3159b76f1e77f74829f27f17bb7211ca23abc.png)

---

<div class="post-metadata">

**Author:** ![srydn](https://avatars.discourse-cdn.com/v4/letter/s/f9ae1b/32.png) [@srydn](https://swi-prolog.discourse.group/u/srydn)\
**Post date:** [June 11, 2023, 12:37pm UTC](https://swi-prolog.discourse.group/t/saving-prolog-query-results-in-python/6628/2 "2023-06-11T12:37:20Z")

</div>

Well, here i did not save yet but it already gives me something like  
[{‘Q’: [[Atom(‘683909’)], [Atom(‘2168325’)], [Atom(‘1420421’)]]}, {‘Q’: [[Atom(‘683909’)], [Atom(‘2168325’)], [Atom(‘1420421’)]]}]

 ![proılogSoruForum](https://global.discourse-cdn.com/free1/uploads/swiprolog/original/2X/3/31d45aaacb824d2da246c1d1a6315f2ebc7d45b7.png)

---

<div class="post-metadata">

**Author:** ![EricGT](https://avatars.discourse-cdn.com/v4/letter/e/f1d935/32.png) [@EricGT](https://swi-prolog.discourse.group/u/EricGT)\
**Post date:** [June 11, 2023, 12:38pm UTC](https://swi-prolog.discourse.group/t/saving-prolog-query-results-in-python/6628/3 "2023-06-11T12:38:34Z")

</div>

Can you please not use screen shots and instead paste the code so that we can use it as text. 🙂

---

<div class="post-metadata">

**Author:** ![srydn](https://avatars.discourse-cdn.com/v4/letter/s/f9ae1b/32.png) [@srydn](https://swi-prolog.discourse.group/u/srydn)\
**Post date:** [June 11, 2023, 12:40pm UTC](https://swi-prolog.discourse.group/t/saving-prolog-query-results-in-python/6628/4 "2023-06-11T12:40:58Z")

</div>

Oh,sure. Here is the code;

```python
from pyswip import Prolog

sentences_list = [] # context list
sentence_list = []
word_list = []
results = []
with open('cumleler.txt',encoding='utf8') as sentences, open('word_list.txt', 'a') as words:

    for sentence in sentences.readlines():
        sentence_list.append(sentence)
    #print(sentence_list)
    for sentence in sentence_list:
          word_list.append(sentence.split())
    #print(word_list)

prolog = Prolog()
prolog.consult("sr_parser.pl")
for word in word_list:
    for i in word:

        try:
            answer = i
            query = list(prolog.query(f"sr_parse(['{answer}'],Q)."))
            print(query)
            #with open('answers.txt','w',encoding='utf8') as cvp:
                #cvp.write(query)
        except:
            print('failed')

```

---

<div class="post-metadata">

**Author:** ![EricGT](https://avatars.discourse-cdn.com/v4/letter/e/f1d935/32.png) [@EricGT](https://swi-prolog.discourse.group/u/EricGT)\
**Post date:** [June 11, 2023, 12:50pm UTC](https://swi-prolog.discourse.group/t/saving-prolog-query-results-in-python/6628/5 "2023-06-11T12:50:07Z")

</div>

Gave it to ChatGPT.

Prompt  
[ChatGPT May 24 Version](https://help.openai.com/en/articles/6825453-chatgpt-release-notes)

Modify code to

- save the prolog.query() results to a file in Python.

```prolog
from pyswip import Prolog

sentences_list = [] # context list
sentence_list = []
word_list = []
results = []
with open('cumleler.txt',encoding='utf8') as sentences, open('word_list.txt', 'a') as words:

    for sentence in sentences.readlines():
        sentence_list.append(sentence)
    #print(sentence_list)
    for sentence in sentence_list:
          word_list.append(sentence.split())
    #print(word_list)

prolog = Prolog()
prolog.consult("sr_parser.pl")
for word in word_list:
    for i in word:

        try:
            answer = i
            query = list(prolog.query(f"sr_parse(['{answer}'],Q)."))
            print(query)
            #with open('answers.txt','w',encoding='utf8') as cvp:
                #cvp.write(query)
        except:
            print('failed')

```

**Completion**

To save the `prolog.query()` results to a file, you can modify the code as follows:

```python
from pyswip import Prolog

sentences_list = [] # context list
sentence_list = []
word_list = []
results = []

with open('cumleler.txt', encoding='utf8') as sentences, open('word_list.txt', 'a') as words:
    for sentence in sentences.readlines():
        sentence_list.append(sentence)
    
    for sentence in sentence_list:
        word_list.append(sentence.split())

prolog = Prolog()
prolog.consult("sr_parser.pl")

with open('answers.txt', 'w', encoding='utf8') as cvp:
    for word in word_list:
        for i in word:
            try:
                answer = i
                query = list(prolog.query(f"sr_parse(['{answer}'], Q)."))
                cvp.write(str(query) + '\n')
                results.extend(query)
            except:
                print('failed')

```

In this modified code, the results of each query are written to the “answers.txt” file using the `cvp.write()` method. The `str(query)` converts the query result to a string format, and `'\n'` is added to move to a new line after each query result. The `results` list is also updated to store the queries’ results if you need to use them later in your code.

---

<div class="post-metadata">

**Author:** ![srydn](https://avatars.discourse-cdn.com/v4/letter/s/f9ae1b/32.png) [@srydn](https://swi-prolog.discourse.group/u/srydn)\
**Post date:** [June 11, 2023, 1:03pm UTC](https://swi-prolog.discourse.group/t/saving-prolog-query-results-in-python/6628/6 "2023-06-11T13:03:49Z")

</div>

I cleaned answers.txt file and changed the codes according to this answer but answers.txt still gives same result, I dont know why .

---

<div class="post-metadata">

**Author:** ![EricGT](https://avatars.discourse-cdn.com/v4/letter/e/f1d935/32.png) [@EricGT](https://swi-prolog.discourse.group/u/EricGT)\
**Post date:** [June 11, 2023, 1:08pm UTC](https://swi-prolog.discourse.group/t/saving-prolog-query-results-in-python/6628/7 "2023-06-11T13:08:47Z")

</div>

Sorry I can’t give you specific help with pyswip as I do not use it and don’t plan to learn it.

Are you aware of [MQI](https://www.swi-prolog.org/pldoc/doc_for?object=section(%27packages/mqi.html%27))?

---

<div class="post-metadata">

**Author:** ![srydn](https://avatars.discourse-cdn.com/v4/letter/s/f9ae1b/32.png) [@srydn](https://swi-prolog.discourse.group/u/srydn)\
**Post date:** [June 11, 2023, 1:10pm UTC](https://swi-prolog.discourse.group/t/saving-prolog-query-results-in-python/6628/8 "2023-06-11T13:10:12Z")

</div>

Oh, there is that too? If it has better functions I should use it instead.

---

<div class="post-metadata">

**Author:** ![srydn](https://avatars.discourse-cdn.com/v4/letter/s/f9ae1b/32.png) [@srydn](https://swi-prolog.discourse.group/u/srydn)\
**Post date:** [June 11, 2023, 1:57pm UTC](https://swi-prolog.discourse.group/t/saving-prolog-query-results-in-python/6628/9 "2023-06-11T13:57:58Z")

</div>

Thanks for your help Eric, I tried using MQI and it is working now.

---

<div class="post-metadata">

**Author:** ![EricGT](https://avatars.discourse-cdn.com/v4/letter/e/f1d935/32.png) [@EricGT](https://swi-prolog.discourse.group/u/EricGT)\
**Post date:** [June 11, 2023, 2:04pm UTC](https://swi-prolog.discourse.group/t/saving-prolog-query-results-in-python/6628/10 "2023-06-11T14:04:00Z")

</div>

> [@srydn](#):
>
> I tried using [MQI](https://www.swi-prolog.org/pldoc/doc_for?object=section(%27packages/mqi.html%27)) and it is working now.

Perhaps you should share what you learned so that others can learn from your experience.

---

<div class="post-metadata">

**Author:** ![srydn](https://avatars.discourse-cdn.com/v4/letter/s/f9ae1b/32.png) [@srydn](https://swi-prolog.discourse.group/u/srydn)\
**Post date:** [June 11, 2023, 2:17pm UTC](https://swi-prolog.discourse.group/t/saving-prolog-query-results-in-python/6628/11 "2023-06-11T14:17:42Z")

</div>

Of course. If anyone wants to work on Python, you should follow the instructions here [swiplserver.prologmqi API documentation](https://www.swi-prolog.org/packages/mqi/prologmqi.html) and to consult your .pl file and query, you should run the code on Python as follows;

```python
from swiplserver import PrologMQI, PrologThread
with PrologMQI() as mqi:
               with mqi.create_thread() as prolog_thread:
                        prolog_thread.query("consult(\"your_prolog_file.pl\").")
                        prolog_thread.query("your_predicate(X,Y).")

```

Hope that helps!
