Reputation: 301
I have the python file trying to modify the other python file here:
file = "PythonFile1.py"
with open(file, "r") as current_file:
lines = current_file.readlines()
for line in lines:
if line != 'sys.stdout = open("test.txt", "w")' or line != "sys.stdout.close()" or line != "import sys":
del lines[lines.index(line)]
with open(file, "w") as current_file:
for line in lines:
current_file.write(line)
print(lines)
And here is the python file trying to be modified:
import sys
sys.stdout = open("test.txt", "w")
sys.stdout.close()
When I run the first python file I get this result in my other python file.
sys.stdout = open("test.txt", "w")
I am looking for the contents of the file to be:
import sys
sys.stdout = open("test.txt", "w")
sys.stdout.close()
I am not sure why it is not catching the lines I want to stay, can anyone help resolve this issue?
Upvotes: 0
Views: 275
Reputation: 68146
Here's what I would do:
magic_lines = [
"sys.stdout = open('test.txt', 'w')",
"sys.stdout.close()",
"import sys"
]
with open(infilepath, 'r') as infile:
lines = infile.readlines()
with open(infilepath, 'w') as outfile:
for line in lines:
if line.strip() in magic_lines:
outfile.write(line)
But it sounds like to me you could nuke and pave the file completely:
from textwraps import dedent
with open(infilepath, 'w') as infile:
infile.write(dedent("""\
import sys
sys.stdout = open("test.txt", "w")
sys.stdout.close()
"""))
Upvotes: 0
Reputation: 1208
with open(file, "w") as current_file:
current_file.write('\n'.join(lines))
You don't need to loop through it and write them, just join the lines and write once directly. When you are looping though it, each and every loop you are replacing what was already in the file, unless you use append mode. Join the lines together and write them directly will be easier.
Read more about the join method
Upvotes: 1