0

I have this code as follow:

print("hello")
print("hello")
print("hello")
print("hello")
x = open("main.py", "a")
x.write("hello")

My objective for this code is for it to print "hello" four times (of which it does), and then after that I want the file to be overwritten so that it contains the word "hello". Ie. I want the python code to be replaced with the word "hello" after the program is finished. However, instead what happens is that it prints "hello" four times, and then the python file just clears itself, is blank, instead of having the word "hello".

I know you can write on other files, but it seems that when writing on the file of itself, things are different. How do I fix this?

  • 2
    Does this answer your question? [Is it possible for a running python program to overwrite itself?](https://stackoverflow.com/questions/291448/is-it-possible-for-a-running-python-program-to-overwrite-itself) – A.Najafi Mar 10 '22 at 18:55
  • Changing what's in the `.py` file won't affect execution whatsoever, just so you know. The file is loaded before execution starts, and the interpreter doesn't keep the file open. – Random Davis Mar 10 '22 at 18:56
  • 2
    You don't close the file but it shouldn't be overwritten anyway because you open the file in append mode. When I run this code it adds the text "Hello" at the end of the script, so it works as designed. – Matthias Mar 10 '22 at 18:58
  • If you want to overwrite the file, why are you opening it in append mode? – martineau Mar 10 '22 at 19:16

1 Answers1

1

You just need to open the file for writing and close it after your write to it like so:

print("hello")
print("hello")
print("hello")
print("hello")
x = open("main.py", "w") #notice the change here
x.write("hello")
x.close() #notice this added line
Eli Harold
  • 2,280
  • 1
  • 3
  • 22