Reputation: 23
I am very new to scripting (this is my first one) and I'm trying to automate network tasks with python. I have built a script that takes a list of AP names from a text file and puts those ap names into the appropriate place within lines of configuration.
What I would really like is to have the final result saved to a file instead of printed to screen, and nothing I've tried yet has worked. Here's my script that prints to screen
f1=open("filename.txt","r")
Lines=f1.readlines()
for line in Lines:
line = line.strip()
o1="ap name " + (line) + " lan port-id 1 enable"
o2="ap name " + (line) + " lan port-id 2 enable"
o3="ap name " + (line) + " lan port-id 3 enable"
print(o1)
print(o2)
print(o3)
f1.close()
So, this works but then I'm having to copy paste it out of the print. I'd love to have it automatically export to a text file, but none of the things I've tried yet have worked. Thanks for the help!
Upvotes: 2
Views: 637
Reputation: 531145
You just need to open a file for writing and tell print
to use that file via the file
argument, instead of sys.stdout
.
with open("filename.txt", "r") as input, open("newfile", "w") as output:
for line in input:
line = line.strip()
for i in [1,2,3]:
print(f"ap name {line} lan port-id {i} enable", file=output)
Upvotes: 1
Reputation: 731
The problem maybe with you opening in "w" mode as it erases and rewrites. Try "a" mode.
f1=open("filename.txt","r")
Lines=f1.readlines()
for line in Lines:
line = line.strip()
o1="ap name " + (line) + " lan port-id 1 enable"
o2="ap name " + (line) + " lan port-id 2 enable"
o3="ap name " + (line) + " lan port-id 3 enable"
print(o1)
print(o2)
print(o3)
f2 = open("result.txt","a")
f2.write("o1: %s\n" % o1)
f2.write("o2: %s\n" % o2)
f2.write("o3: %s\n" % o3)
f2.close()
f1.close()
Upvotes: 0