-2
open_txt_file = open("codeharrytextfile.txt","w")  #file point
b = open_txt_file.write("test it theory")
print(b)

enter image description here

I have tried writing to existing textfile and I was expecting it to display the updated text written to it whereas I am getting value - which is length of added "text"

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 2
    The `write` function does not return the actual text. Look up its [documentation](https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects): `f.write(string) writes the contents of string to the file, returning the number of characters written.` Looking at the documentation is always the first thing you should do when you don't understand what a function you're using is doing. – Random Davis Feb 18 '22 at 18:05
  • yes, that's how write works. Don't forget closing the file since you are opening it but never closing it –  Feb 18 '22 at 18:05

2 Answers2

0

You are printing to console the file handler, which isn't what you want. This code should do what you want.

open_txt_file = open("codeharrytextfile.txt","w")  #file point
text = "test is theory"
open_txt_file.write(text)
print(text)

matiasop
  • 3
  • 2
0

Per the documentation for write(b) (emphasis added):

Write the given bytes-like object, b, and return the number of bytes written (always equal to the length of b in bytes, since if the write fails an OSError will be raised). Depending on the actual implementation, these bytes may be readily written to the underlying stream, or held in a buffer for performance and latency reasons.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578