无法使用"写"将输出文本文件格式化为所需的表单函数Python

时间:2017-03-22 17:57:48

标签: python

我无法根据需要格式化文本文件的输出。我已经骗了将近一个小时,无济于事,这让我很生气。我希望前四个浮点数在一行上,接下来的10个值由新行划分。

    if not (debug_flag>0):
        text_file = open("Markov.txt", "w")
        text_file.write("%.2f,%.2f,%.2f,%.2f" % (prob_not_to_not,prob_not_to_occured, prob_occured_to_not, prob_occured_to_occured))

        for x in xrange(0,10):
             text_file.write("\n%d" % markov_sampler(final_probability))

        text_file.close()

有谁知道这是什么问题?我得到的输出全部在1行。

1 个答案:

答案 0 :(得分:1)

您必须将换行符放在第一行的末尾才能生效。 您的文本编辑器也可以配置为\ r \ n行尾(如果您使用的是记事本),在这种情况下,您应该看到同一行中的所有内容。

具有所需输出的代码可能看起来像这样

if not (debug_flag>0):
    text_file = open("Markov.txt", "w")
    text_file.write("%.2f,%.2f,%.2f,%.2f\n" % (prob_not_to_not,prob_not_to_occured, prob_occured_to_not, prob_occured_to_occured))

    for x in xrange(0,10):
         text_file.write("%d\n" % markov_sampler(final_probability))

    text_file.close()