Home > Back-end >  how make changes with python code to other python code
how make changes with python code to other python code

Time:12-16

name = input("what's your name?")
if name == "John"
#it will make changes to another code
with open('example.py') as f:
    f.write("John")

example.py before:

names = "Jack"

example.py after:

names = "Jack", "John"

So i want insert name to other python file with python code how can i?

CodePudding user response:

Your approach is somewhat on the line, however there's a more pythonic way to do it:

>>> main.py
import example # example.py
name = input("what's your name?")
if name == "John":
    example.names.append(name) # append John
>>> example.py
names = ["Jack"]

Note: This approach saves the variables until the code is executed. However, if you want permanent changes:

  • Create another names.txt file
>>> main.py
name = input("what's your name?")
if name == "John":
    with open("names.txt","a") as f:
        f.write(f", {name}")
>>> names.txt
Jack, John
>>> example.py
with open("names.txt","r") as f:
    names = f.read().split(', ')

CodePudding user response:

you have to add ,'w' to the open method to be able to write in it

with open('example.py', 'w') as f:

then you can do something like this

    
file = open('example.py', "r")
filecontents = ""
for line in file:
    change = ""
    if("names = " in line):
        change = line.strip()   ',"jhon"'

    filecontents  = change   "\n"
    
file.close()
write_file = open("example.py", "w")
write_file.write(filecontents)
write_file.close()
  • Related