-1

Here I show a for loop which doesn't work well. What it prints is right while it only writes the last line to the .txt file. For example, it prints:

[0.173] [robe]
[0.493] [tree]
[0.274] [book]

But the file data01.txt has only one line:

[0.274] [book]

What I expect is the file includes all it prints.

for a_word in phrase_model.keys():
    for b_word in phrase_model.keys():
        a_val = phrase_model[a_word]
        b_val = phrase_model[b_word]
        c_word = [a_word, b_word]
        cos_dis = cosine_similarity(a_val, b_val)
        print(str(cos_dis) + str(c_word))
        f = open('data01.txt', 'w')
        f.write(str(cos_dis) + str(c_word))

f.close()
thomas2019
  • 27
  • 3
  • Change ‘w’ to ‘a’. – JayPeerachai Oct 01 '19 at 08:24
  • Change this `'w'` write mode to `'a'` append mode – shaik moeed Oct 01 '19 at 08:26
  • 2
    Ideally, you want to open the file once, and write everything to it rather than opening it many times in append mode (and only close it once). Have a look at the [`with open(...`](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files) syntax. – Holloway Oct 01 '19 at 08:27
  • [How do you append to a file in Python?](https://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file-in-python) — but you would be better off opening the file before the loop instead of opening it repeatedly inside the loop. – khelwood Oct 01 '19 at 08:27

3 Answers3

0

you are using write mode

f = open('data01.txt', 'w')

Instead you should use append mode

f = open('data01.txt', 'a')

This is the reason the lines are overwritten and you see only last line. Do read about different modes here

pvpkiran
  • 25,582
  • 8
  • 87
  • 134
0

You have opened your file in write mode.

        f = open('data01.txt', 'w')

This will start overwriting the file from the beginning.

You should use the append mode.

        f = open('data01.txt', 'a')

This will append to the file instead of overwriting.

rdas
  • 20,604
  • 6
  • 33
  • 46
0

You open the file for writing repeatedly in each iteration, and thus it is constantly truncated.

Just open the file once before the loops.

f = open('data01.txt', 'w')

for a_word in phrase_model.keys():
    for b_word in phrase_model.keys():
        a_val = phrase_model[a_word]
        b_val = phrase_model[b_word]
        c_word = [a_word, b_word]
        cos_dis = cosine_similarity(a_val, b_val)
        print(str(cos_dis) + str(c_word))
        f.write(str(cos_dis) + str(c_word))

f.close()