Python syntaxerror: unexpected character after line continuation character - python

I'm just starting python so am most likely just doing something stupid. I'm reading data off of a table and need to put them into columns in a txt file. I cannot convince my code to create a new line.
Here is my code-
file = open("test_m.rdb")
table = open('table.txt', 'w+')
trash = file.readline()
trash = file.readline()
data = file.readline()
i = data.split()
flux = i[2]
observed = i[4]
table.write(flux + " " + observed,)
while 1:
line = file.readline()
i = line.split()
try:
flux = i[2]
observed = i[4]
except IndexError:
break
table.write(\nflux + " " + observed)
table.close()
And the error reads-
File "PlotRdbFile.py", line 24
table.write(\nflux + " " + observed)
^
SyntaxError: unexpected character after line continuation character
Thank you in advance for finding my mistake.

table.write(\nflux + " " + observed)
should be
table.write("\n" + flux + " " + observed)
or alternatively
table.write("\n{} {}".format(flux, observed))
More information about format() if you are curious.

Related

File not being created/written in

This is my code:
org = "na"
OutputFile = open("F&FHOutput.txt", "a")
#Part 1
with open("input.txt") as file:
for line in file:
string,letter = line.strip().split(",")
print(string + "," + letter + "," + string.replace(letter, ""))
OutputFile.write(string + "," + letter + "," + string.replace(letter, ""))
#Part 2
def remove_strings_recursive(lines):
if not lines:
return ""
word,letter = lines[0].rstrip().split(',')
org = word
word = word.replace(letter, '')
print(org + "," + letter + "," + word)
OutputFile.write(org + "," + letter + "," + word)
return word + '\n' + remove_strings_recursive(lines[1:])
with open('input.txt', 'r') as file:
lines = file.readlines()
result = remove_strings_recursive(lines)
OutputFile.close()
I am trying to have it take the same things that are being printed and put them into a new file that the program creates if the file doesn't exist. Every time I run the code, everything works fine but the output file is nowhere to be found. Could someone please help? (Sorry about the messy code)
Your file name has a special character (&), which can cause problems. Try changing the file name to a more standard one.

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"

Average in file

I have this code
def PromNotas():
archivo = open ("archivo.csv","r")
archivo2 = open ("archivo2.csv","w")
for reg in archivo:
reg = reg.strip("\n")
datos = reg.split(",")
prom = (datos[1] + datos[2])/2
reg2 = datos[0] + "," + datos[1] + "," + datos[2] + "," + str(prom)
if prom >= 7:
reg2 = reg2 + "," + "Aprobado\n"
else:
reg2 = reg2 + "," + "Desprobado\n"
archivo2.write(reg2)
archivo.close()
archivo2.close()
The csv file looks like this:
Matt,7,8
John,9,6
Jim,6,7
All the code works but the line of prom = (datos[1] + datos[2])/2 it says that the list index is out of range. Does anyone know something.
Given the script and the input csv file the program runs correctly for me.
The only thing that I changed is casting the numbers to integers prom = (int(datos[1]) + int(datos[2]))/2
Make sure that you are using the correct input file and check that there aren't any empty lines or lines with less than 2 arguments on them.(2 commas)
Catch the error and print datos and reg in the except suite. Are they what you expected? Are there any blank lines in your file? Do all lines in the file have three columns.?
...
datos = reg.split(",")
try:
prom = (datos[1] + datos[2])/2
except IndexError as e:
print('datos:{} | reg:{}'.format(datos, reg))
#raise
reg2 = datos[0] + "," + datos[1] + "," + datos[2] + "," + str(prom)
...
Or, if you don't mind a lot of stuff printing, just print reg and datos just before the assignment to prom. Then the last print before the exception should give you a clue to what is wrong.
...
datos = reg.split(",")
print('datos:{} | reg:{}'.format(datos, reg))
prom = (datos[1] + datos[2])/2
...
When you split reg it must produce a list with less than three items so the file either has blank lines or lines with less than two columns.

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.

overwrite words in text file with python

I created a text file that contains in the first line a counter of created users and the rest of the lines the text contains user name, password..
for example:
2
username Name Last_name Password
username1 Name Last_name1 Password1
I'm using the following commands:
def SaveDatA(self):
#if self.CheckValid() == False:
#return
with open("data.txt","a") as f:
f.write(self.userEntry.get() + " " + self.NameEntry.get() + " " + self.LastEntry.get()+ " " + self.PasswordEntry.get() + "\n")
self.counter += 1
I want to update the counter to the first line
Do you want this?
f1_lines = open('data.txt', 'r').readlines()
with open('data.txt','w') as f:
f.write(self.userEntry.get() + " " + self.NameEntry.get() + " " + self.LastEntry.get()+ " " + self.PasswordEntry.get() + "\n")
self.counter += 1
f1_lines[0]=str(self.counter)+'\n'
f.write(''.join(f1_lines))
With readlines() you create a list contain all of lines in the file so you change the first index of that list with f1_lines[0]=str(self.counter)+'\n' then rewrite it in to the file !
After a lot of trials this code work's:
with open("data.txt","a") as f:
f.write(self.userEntry.get() + " " + self.NameEntry.get() + " " + self.LastEntry.get()+ " " + self.PasswordEntry.get() + "\n")
self.counter += 1
fileCopy = open('data.txt', 'r').readlines()
fileCopy[0] = fileCopy[0][1:]
with open("data.txt","w") as f:
f.write(str(self.counter)+" ")
f.write("".join(fileCopy))
but maybe there is another better way ?

Categories