简体   繁体   中英

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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