Python - Creating a program that changes itself

Asked

Viewed 66 times

0

I would like to create a program that is able to change itself, that is, I run the script, and it changes the script itself, creating a kind of bookmark.

The big problem is that I can’t change the program when it’s running, as I did below:

arq = open("./01_programa_alterar.py")
lines = arq.readlines()

x = False  # lines[4] = "x = True\n"

if x:
    print("Você Alterou o script")
else:
    print("Script não alterado")


#----mudar script----
lines[4] = "x = True\n"  # Pulo do gato

for line in lines:
    arq.write(line)
#--------------------

arq.close()

I would like to know if there is any module that makes this change :(

  • Have you tried putting the arq.close() before the x = False ?

  • first I read the file in 'r' mode then I closed it, then I opened it again in "w"

1 answer

0

This is how I made it work:

#Ler arquivo
arq = open(__file__, 'r')
lines = arq.readlines() #Leremos por aqui
arq.close()

x = False

if x:
    print("Você Alterou o script")
else:
    print("Script não alterado")

#Escrever arquivo (Não ler linhas)
arq = open(__file__, 'w')

#----mudar script----
lines[5] = "x = True\n"

for line in lines:
    arq.write(line)
#--------------------

arq.close()

I was forgetting to close the file and then open it again with, only on as "w" open(file,'w') ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.