Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell python to edit another python file?

Tags:

python

file

edit

Right now, I have file.py and it prints the word "Hello" into text.txt.

f = open("text.txt") f.write("Hello") f.close()

I want to do the same thing, but I want to print the word "Hello" into a Python file. Say I wanted to do something like this:

f = open("list.py") f.write("a = 1") f.close

When I opened the file list.py, would it have a variable a with a value 1? How would I go about doing this?

like image 493
Elle Nolan Avatar asked Jun 25 '26 23:06

Elle Nolan


2 Answers

If you want to append a new line to the end of a file

with open("file.py", "a") as f:
    f.write("\na = 1")

If you want to write a line to the beginning of a file try creating a new one

with open("file.py") as f:
    lines = f.readlines()

with open("file.py", "w") as f:
    lines.insert(0, "a = 1")
    f.write("\n".join(lines))
like image 181
Greg Avatar answered Jun 27 '26 13:06

Greg


with open("list.py","a") as f:
    f.write("a=1")

This is simple as you see. You have to open that file in write and read mode (a). Also with open() method is safier and more clear.

Example:

with open("list.py","a") as f:
    f.write("a=1")
    f.write("\nprint(a+1)")

list.py

a=1
print(a+1)

Output from list.py:

>>> 
2
>>> 

As you see, there is a variable in list.py called a equal to 1.

like image 38
GLHF Avatar answered Jun 27 '26 12:06

GLHF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!