1

I am trying to write some content to the file. The problem is that the large contents get split over multiple lines which I don't want to do. Here is the code:-

from stackapi import StackAPI
SITE = StackAPI('stackoverflow')
SITE.max_pages=1
SITE.page_size=1

questions = SITE.fetch('questions', min=20, tagged='python', sort='votes')

with open('python_qna.txt', 'w') as file:
    for quest in questions['items']:
        if 'title' not in quest or quest['is_answered'] == False:
            continue
        title = quest['title']
        question_id = quest['question_id']
        top_answer = SITE.fetch('questions/' + str(question_id) + '/answers', order = 'desc', sort='votes', filter='!-.7zMlMaANYq')
        file.write('- - ' + title + '\n')
        file.write('  - ' + top_answer['items'][0]['body'])

The Sample output of the above code is:-

- - What does the "yield" keyword do?
  - <p>To understand what <code>yield</code> does, you must understand what <em>generators</em> are. And before generators come <em>iterables</em>.</p>

<h2>Iterables</h2>
:
:
After all the lines
End of the answer line!

What should be done so that the file has a single line of question and then a single line of answer structure?

The final structure of the file should be like:-

- - Question 1
  - Answer 1
- - Question 2
  - Answer 2
- - Question 3
  - Answer 3
.
.
.
- - Question n
  - Answer n
Shashishekhar Hasabnis
  • 1,636
  • 1
  • 15
  • 36

1 Answers1

0

The string.splitlines() method did work for me:-

top_answer = " ".join(top_answer.splitlines())
Shashishekhar Hasabnis
  • 1,636
  • 1
  • 15
  • 36