Writing Data to an output file in Python - python

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!

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)

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()

Related

I want this function to create notepad file with each new record on new line "\n" i have tried many times but vain

def print_(self, trv):
rec = " "
for line in trv.get_children():
rec += " "
for value in trv.item(line)['values']:
rec += str(value) + " "
textfile = open('Reportnew.txt', 'w')
textfile.write(rec)
textfile.close()
I can barely understand your question because it's not formatted properly.
But if you want to append new lines use this
with open('Reportnew.txt', 'a') as textfile: #notice the 'a' instead of 'w'
textfile.write(rec) #can write "\n" + rec OR rec + "\n" if rec doesn't have \n in it already
Or this
with open('Reportnew.txt', 'a') as textfile: #notice the 'a' instead of 'w'
textfile.write("\n")
textfile.write(rec)
Are you looking for something like this:
def print_(self, trv):
rec = ""
for line in trv.get_children():
rec += " ".join(map(str, trv.item(line)['values'])) + "\n"
with open("Reportnew.txt", "w") as file:
file.write(rec)
I used " ".join(...) to join all of the items adding spaces in between. I also added "\n" at the end of each record.

Multiple else condition in python

I have python script with will read each IP from file and install agent on that IP using password, there are 5-6 passwords and if one password doesn't work it should try with other all passwords one by one.
This is my script:
##Reading values from SucessfullIp.txt
with open('/root/nix_bsd_mac_inventory-master/SucessfullIp.txt') as f:
ips = set(line.rstrip() for line in f)
##Reading Unique Ip's values
with open("/root/nix_bsd_mac_inventory-master/Unique.txt") as fp:
for line in fp:
line = line.rstrip()
## Comparing unique ip's if ip is already has scanned
if line in ips:
print('{}: Ip is Already Tried: '.format(line))
else:
##Creating inventory.cfg file on the fly for each ip
f3 = open("/root/nix_bsd_mac_inventory-master/inventory.cfg", "w")
print "Processing Ip: " + line
f3.write("[device42_access]" + "\n" +
"base_url = https://1.8.0.3" + "\n" +
"username = uname" + "\n" +
"secret = abcd" + "\n" +
"[discover]" + "\n" +
"cpu= true" + "\n" +
"hardware = true" + "\n" +
"memory = true" + "\n" +
"[access]"+ "\n" +
"credentials = username:passowrd1" + "\n" + ##here we are giving credentials and we have 5-6 passwords
f3.close()
p = subprocess.Popen(["./d42_linux_autodisc_v620"], stdout=subprocess.PIPE) ##This script will require inventory.cfg file created above
p1 = str(p.communicate())
if '1 devices were successfully added/updated' in p1:
print ('Sucessfull Completed Ip: ' +line)
f6 = open("/root/nix_bsd_mac_inventory-master/SucessfullIp.txt","a")
f6.write("\n"+line)
f6.close()
else:
print "Unsuccessfull"
##here want it to check it with other passwords as well
You should iterate over a list of your passwords and break out of the loop if one is successful.
You had a syntax error in the following snippet:
"credentials = username:passowrd1" + "\n" +
This should not end with a + as you are not concatenating anything else to the string.
It will be useful for you to look up break, continue, and else statements that you can use with loops as I have used them in the answer.
I have removed all of your comments, and added comments of my own to explain the logic.
with open("/root/nix_bsd_mac_inventory-master/Unique.txt") as fp:
for line in fp:
line = line.rstrip()
if line in ips:
print('{}: Ip is Already Tried: '.format(line))
continue # Continue means it will skip to the next password
passwords = ['password1', 'password2', 'password3']
for password in passwords:
f3 = open("/root/nix_bsd_mac_inventory-master/inventory.cfg",
"w")
print "Processing Ip: " + line
f3.write("[device42_access]" + "\n" +
"base_url = https://1.8.0.3" + "\n" +
"username = uname" + "\n" +
"secret = abcd" + "\n" +
"[discover]" + "\n" +
"cpu= true" + "\n" +
"hardware = true" + "\n" +
"memory = true" + "\n" +
"[access]" + "\n" +
"credentials = username:" + password + "\n" # Fixed typo here
f3.close()
p = subprocess.Popen(["./d42_linux_autodisc_v620"],
stdout=subprocess.PIPE)
p1 = str(p.communicate())
if '1 devices were successfully added/updated' in p1:
print('Sucessfull Completed Ip: ' + line)
f6 = open("/root/nix_bsd_mac_inventory-master/SucessfullIp.txt", "a")
f6.write("\n" + line)
f6.close()
break # If successful it breaks, so don't need an else
print "Password %s Unsuccessfull" % password
else:
# This happens when there are no more passwords to attempt
print "No passwords were successful"
You can do it using a for loop and a single else:
for password in list_of_password:
...
"credentials = username:" + password + "\n"
...
if '1 devices were successfully added/updated' in p1:
...
break
else:
print "Unsuccessfull"

Python: Attempting to append to file but nothing is being written

This section of code should write an input and another variable (Score) to a text file. The program asks for the input (so the if statement is definitely working) and runs without errors, but the text file is empty. Oddly, copying this code to an empty python file and running it works without errors. What is happening here?
if Score > int(HighScores[1]):
print("You beat the record with " + str(Score) + " points!")
Name = input("What is your name?")
BestOf = open("High Scores.txt", "w").close()
BestOf = open("High Scores.txt", "a")
BestOf.write(Name + "\n")
BestOf.write(str(Score))
I didn't close the file after appending.
BestOf.close()
fixed it
Try opening the file in 'w+' mode. This will create the file if it doesn't exist.
You can also check if the file exits using the 'os' module.
import os;
if Score > int(HighScores[1]):
print("You beat the record with " + str(Score) + " points!")
name = input("What is your name?")
if os.path.isfile("Scores.txt"):
fh = open("Scores.txt", "a")
else:
fh = open("Scores.txt", "w+")
fh.write(name + "\n")
fh.write(str(Score))
fh.close()

python wont write even when I use f.close

I'm trying to write some code that outputs some text to a list. output is a variable that is a string which is the name of the file to be written. However whenever I look at the file nothing is written.
with open(output, 'w') as f:
f.write("Negative numbers mean the empty space was moved to the left and positive numbers means it was moved to the right" + '\n')
if A == True:
the_h = node.h
elif A== False:
the_h = 0
f.write("Start " + str(node.cargo) + " " + str(node.f) +" " +str(the_h)+" " + '\n')
if flag == 0:
flag = len(final_solution)
for i in range (1,flag):
node = final_solution[i]
f.write(str(node.e_point - node.parent.e_point) + str(node.cargo) + " " + str(node.f) +'\n')
f.close()
Program looks ok, check if the output is set ok, I set as a dummy filename, it worked, presuming code within the block after open has no compiler/interpreter error. The output file should be in the same directory where the source is.
output = "aa.txt"
with open(output, 'w') as f:
f.write("Negative numbers mean the empty space was moved to the left and positive numbers means it was moved to the right" + '\n')
if A == True:
the_h = node.h
elif A== False:
the_h = 0
f.write("Start " + str(node.cargo) + " " + str(node.f) +" " +str(the_h)+" " + '\n')
if flag == 0:
flag = len(final_solution)
for i in range (1,flag):
node = final_solution[i]
f.write(str(node.e_point - node.parent.e_point) + str(node.cargo) + " " + str(node.f) +'\n')
f.close()
You should not add f.close(), as the with statement will do it for you. Also ensure you don't reopen the file elsewhere with open(output, 'w') as that will erase the file.

Python: File Writing Adding Unintentional Newlines on Linux Only

I am using Python 2.7.9. I'm working on a program that is supposed to produce the following output in a .csv file per loop:
URL,number
Here's the main loop of the code I'm using:
csvlist = open(listfile,'w')
f = open(list, "r")
def hasQuality(item):
for quality in qualities:
if quality in item:
return True
return False
for line in f:
line = line.split('\n')
line = line[0]
# print line
itemname = urllib.unquote(line).decode('utf8')
# print itemhash
if hasQuality(itemname):
try:
looptime = time.time()
url = baseUrl + line
results = json.loads(urlopen(url).read())
# status = results.status_code
content = results
if 'median_price' in content:
medianstr = str(content['median_price']).replace('$','')
medianstr = medianstr.replace('.','')
median = float(medianstr)
volume = content['volume']
print url+'\n'+itemname
print 'Median: $'+medianstr
print 'Volume: '+str(volume)
if (median > minprice) and (volume > minvol):
csvlist.write(line + ',' + medianstr + '\n')
print '+ADDED TO LIST'
else:
print 'No median price given for '+itemname+'.\nGiving up on item.'
print "Finished loop in " + str(round(time.time() - looptime,3)) + " seconds."
except ValueError:
print "we blacklisted fool?? cause we skippin beats"
else:
print itemname+'is a commodity.\nGiving up on item.'
csvlist.close()
f.close()
print "Finished script in " + str(round(time.time() - runtime, 3)) + " seconds."
It should be generating a list that looks like this:
AWP%20%7C%20Asiimov%20%28Field-Tested%29,3911
M4A1-S%20%7C%20Hyper%20Beast%20%28Field-Tested%29,4202
But it's actually generating a list that looks like this:
AWP%20%7C%20Asiimov%20%28Field-Tested%29
,3911
M4A1-S%20%7C%20Hyper%20Beast%20%28Field-Tested%29
,4202
Whenever it is ran on a Windows machine, I have no issue. Whenever I run it on my EC2 instance, however, it adds that extra newline. Any ideas why? Running commands on the file like
awk 'NR%2{printf $0" ";next;}1' output.csv
do not do anything. I have transferred it to my Windows machine and it still reads the same. However, when I paste the output into Steam's chat client it concatenates it in the way that I want.
Thanks in advance!
This is where the problem occurs
code:
csvlist.write(line + ',' + medianstr + '\n')
This can be cleared is you strip the space
modified code:
csvlist.write(line.strip() + ',' + medianstr + '\n')
Problem:
The problem is due to the fact you are reading raw lines from the input file
Raw_lines contain \n to indicate there is a new line for every line which is not the last and for the last line it just ends with the given character .
for more details:
Just type print(repr(line)) before writing and see the output

Categories