【问题标题】:How to write only a single line to file?如何只将一行写入文件?
【发布时间】:2018-12-13 10:03:49
【问题描述】:

我正在尝试将一些内容写入文件。问题是大内容被分成多行,我不想这样做。这是代码:-

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'])

上述代码的示例输出为:-

- - 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!

应该怎么做才能使文件有一行问题和一行答案结构?

文件的最终结构应该是这样的:-

- - Question 1
  - Answer 1
- - Question 2
  - Answer 2
- - Question 3
  - Answer 3
.
.
.
- - Question n
  - Answer n

【问题讨论】:

  • 在写入文件之前尝试替换您的问题正文\ns。
  • 任何地方都没有“\n”。
  • top_answer['items'][0]['body'] 中有 很多\n
  • 我在这里找到了答案:- stackoverflow.com/questions/13298907/…

标签: python-3.x


【解决方案1】:

string.splitlines() 方法确实对我有用:-

top_answer = " ".join(top_answer.splitlines())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    • 2015-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多