简体   繁体   English

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

[英]Write output of a while loop to multiple text files

I have two issues: the while loop is finishing at 1.1 not 1 and how can I save a text file for each value of alpha_min as the way I wrote the code, only the last message of alpha_min is being saved in the text file? 我有两个问题: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()

You should only open the file once and close it at the end, because what you're doing right now is overwriting the file at each iteration (or you could use append rather than 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM