将while循环的输出写入多个文本文件

时间:2017-05-15 19:09:05

标签: python printing while-loop text-files

我有两个问题:while循环在1.1而不是1完成,我如何为每个alpha_min值保存一个文本文件,就像我编写代码的方式一样,只有alpha_min的最后一条消息保存在文本中文件?

alpha_min = 0
alpha_max = 1

while (alpha_min < alpha_max):
    alpha_min += 0.1
    #Length of message 
    length_msg = (alpha_min * n)
    len_msg = int(length_msg)
    print(alpha_min)

    #Generates random messages, 1D vectora consisting of 1s and 0s for different values of alpha
    msg = np.random.randint(2, size= len_msg)
    print(msg)

    #Save messages in text format representing each bit as 0 or 1 on a separate line
    msg_text_file = open("msg_file.txt", "w")  # Path of Data File
    msg_text_file.write("\n".join(map(lambda x: str(x), msg)))
    msg_text_file.close()

1 个答案:

答案 0 :(得分:1)

你应该只打开一次文件并在最后关闭它,因为你现在正在做的是在每次迭代时覆盖文件(或者你可以使用append而不是write)

alpha_min = 0
alpha_max = 1



while (alpha_min < alpha_max):
    alpha_min += 0.1
    #Length of message 
    length_msg = (alpha_min * n)
    len_msg = int(length_msg)
    print(alpha_min)

    #Generates random messages, 1D vectora consisting of 1s and 0s for different values of alpha
    msg = np.random.randint(2, size= len_msg)
    print(msg)

    #Save messages in text format representing each bit as 0 or 1 on a separate line
    msg_text_file = open("msg_file_{}.txt".format(alpha_min), "w")  # Path of Data File
    msg_text_file.write("\n".join(map(lambda x: str(x), msg)))
    msg_text_file.close()