-2

When I use a write function in this code nothing happens, read works fine. Any reason why?

if userinp == ('save'):
    save = open("save.txt",'r')
    print(save.read())
    save = open("save.txt",'a')
    save.write("pop")

save.txt: test

output: test

desired output: pop

thank you for the downvotes :)

3 Answers3

0

To replace the word 'test' in b.txt with 'pop', do the following:

if userinp == ('save'):
    save = open("b.txt",'r')
    print(save.read())
    save = open("b.txt",'w')
    save.write("pop")
    save.close()

The option of 'a' in save = open() appends the word 'pop' to the file, the 'w' option overwrites the content.

tda
  • 2,045
  • 1
  • 17
  • 42
0

Perhaps the content is in the buffer and not written to file yet.

You can add save.close() after writing so that the buffer is flushed out to the file.

Alternatively, you can do save.flush() to perform a manual flush without closing the file.

sid-m
  • 1,504
  • 11
  • 19
0

FYI: with is taking care of 'close` calls so that we don't have to:

with open('foo.txt', 'w') as f:
    f.write('bar')
meissner_
  • 556
  • 6
  • 10