0

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()
4
  • To fix your first problem, change the < on line 4 to <= Commented May 15, 2017 at 19:11
  • @Qwerty didn't get you sorry Commented May 15, 2017 at 19:12
  • why not? what dont you get Commented May 15, 2017 at 19:14
  • @Qwerty I tried it still didnt work, im using python 2.7 Commented May 15, 2017 at 19:25

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

6 Comments

still generated a single text file for some odd reason
What it's doing is generating a single file and putting all the contents in it. If you want one file per iteration, you have to have a different name for it (and move back the open and the close to your loop). For example, f = open("message_{}.txt".format(alpha_min), 'w') and then do what you want.
do i do this before the while loop or inside the loop?
thank you so much man! Is it possible to save multiple images resulting from a for loop? as only the last image is being saved simialrly to the =text file scenario
I don't really understand the question... what do you mean by "multiple images" ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.