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.
Related
After packing my program I decided to test it out to make sure it worked, a few things happened, but the main issue is with the Save_File.
I use a Save_File.py for data, static save data. However, the frozen python file can't do anything with this file. It can't write to it, or read from it. Writing says saved successful but on load it resets all values to zero again.
Is it normal for any .py file to do this?
Is it an issue in pyinstaller?
Bad freeze process?
Or is there some other reason that the frozen file can't write, read, or interact with files not already inside it? (Save_File was frozen inside and doesn't work, but removing it causes errors, similar to if it never existed).
So the exe can't see outside of itself or change within itself...
Edit: Added the most basic version of the save file, but basically, it gets deleted and rewritten a lot.
def save():
with open("Save_file.py", "a") as file:
file.write("healthy = " + str(healthy) + "\n")
file.write("infected = " + str(infected) + "\n")
file.write("zombies = " + str(zombies) + "\n")
file.write("dead = " + str(dead) + "\n")
file.write("cure = " + str(cure) + "\n")
file.write("week = " + str(week) + "\n")
file.write("infectivity = " + str(infectivity) + "\n")
file.write("infectivity_limit = " + str(infectivity_limit) + "\n")
file.write("severity = " + str(severity) + "\n")
file.write("severity_limit = " + str(severity_limit) + "\n")
file.write("lethality = " + str(lethality) + "\n")
file.write("lethality_limit = " + str(lethality_limit) + "\n")
file.write("weekly_infections = " + str(weekly_infections) + "\n")
file.write("dna_points = " + str(dna_points) + "\n")
file.write("burst = " + str(burst) + "\n")
file.write("burst_price = " + str(burst_price) + "\n")
file.write("necrosis = " + str(necrosis) + "\n")
file.write("necrosis_price = " + str(necrosis_price) + "\n")
file.write("water = " + str(water) + "\n")
file.write("water_price = " + str(water_price) + "\n")
file.write("air = " + str(air) + "\n")
file.write("blood = " + str(blood) + "\n")
file.write("saliva = " + str(saliva) + "\n")
file.write("zombify = " + str(zombify) + "\n")
file.write("rise = " + str(rise) + "\n")
file.write("limit = int(" + str(healthy) + " + " + str(infected) + " + " + str(dead) + " + " + str(zombies) + ")\n")
file.write("old = int(1)\n")
Clear.clear()
WordCore.word_corex("SAVING |", "Save completed successfully")
time.sleep(2)
Clear.clear()
player_menu()
it's probably because the frozen version of the file (somewhere in a .zip file) is loaded and never the one you're writing (works when the files aren't frozen)
That's bad practice to:
- have a zillion global variables to hold your persistent data
- generate code in a python file just to evaluate it back again (it's _self-modifying code_).
If you used C or C++ language, would you generate some code to store your data then compile it in your new executable ? would you declare 300 globals? I don't think so.
You'd be better off with json data format and a dictionary for your variables, that would work for frozen or not frozen:
your dictionary would be like:
variables = {"healthy" : True, "zombies" : 345} # and so on
Access your variables:
if variables["healthy"]: # do something
then save function:
import json
def save():
with open("data.txt", "w") as file:
json.dump(variables,file,indent=3)
creates a text file with data like this:
{
"healthy": true,
"zombies": 345
}
and load function (declaring variables as global to avoid creating the same variable, but local only)
def load():
global variables
with open("data.txt", "r") as file:
variables = json.load(file)
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"
I've written a little script that scans a text file in the below format.
Then outputs a different text file with the redirected URLs, only if there is a redirection. Otherwise, I wanted to print out "No redirection". But for some reason, the exact opposite happens.
Below is my code, could you please explain me what I did wrong?
import urllib.request
inc_input = input("Please enter the file name\n")
file_name = open(inc_input)
f = open('output.txt', 'w')
for line in file_name:
eachurl = line.strip()
redirected = urllib.request.urlopen(eachurl)
finalurl = redirected.geturl()
if eachurl == finalurl:
f.write(eachurl + "\t" + finalurl + "\n")
else:
f.write(eachurl + "\t" + "No redirection" + "\n")
f.close()
Your logic seems opposite to what you expect, I've added comments to clarify:
if eachurl == finalurl:
# no redirection happened since we're in the original url (==)
f.write(eachurl + "\t" + finalurl + "\n")
else:
# redirection happened, different url
f.write(eachurl + "\t" + "No redirection" + "\n")
Use not to reverse the condition or reverse the bodies. Currently the message is misleading.
if eachurl != finalurl: #when the urls are not same, it's a redirection
f.write(eachurl + "\t" + finalurl + "\n")
else:
f.write(eachurl + "\t" + "No redirection" + "\n")
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 ?
i'm having a problem with the python's csv reader. The problem is that i want to open and read different csv files, but he keeps on reading always the same one.
from csv import reader
alphabet = ["a", "b", "c"]
for letter in alphabet:
csv_file = open('/home/desktop/csv/' + letter + '.csv', 'r')
csv_data = reader(csv_file)
The problem is that he seems to open the other files, but he keep on reading always the first file.
Is there a way to "clean" the reader or make him read another file? I even tried to close the csv file, but it didn't work.
The full code is this
from csv import reader
#Orario
orario_csv_file = '/home/andrea/Scrivania/orario.csv'
orario_csv = open(orario_csv_file)
orario_data = reader(orario_csv)
orario = []
#Corsi
corsi = ["EDILIZIA", "EDILE-ARCHIT", "ELETTRONICA", "TECNOLOGIE_DI_INTERNET", "INFORMATICA", "GESTIONALE", "ENERGETICA", "MECCANICA", "CIVILE_ED_AMBIENTALE", "MEDICA", "ENGINEERING_SCIENCES"]
giorni = ["Lun", "Mar", "Mer", "Gio", "Ven"]
for row in orario_data:
orario.append(row)
for corso in corsi:
nome_corso_file = '/home/andrea/Scrivania/xml/' + corso + '.xml'
nome_corso_xml = open(nome_corso_file, 'wt')
nome_corso_xml.write('<?xml version="1.0"?>' + "\n")
nome_corso_xml.write('<orario>' + "\n")
nome_csv = corso + '_csv'
nome_csv = '/home/andrea/Scrivania/csv/' + corso + '.csv'
nome_corso_csv = open(nome_csv, 'rt')
corso_data = reader(nome_corso_csv)
nome_corso_xml.write(' <corso name="' + corso + '">' + "\n")
for a in range(0, 3):
nome_corso_xml.write(' <anno num="' + str(a+1) + '">' + "\n")
for j in range(1, 6):
nome_corso_xml.write(' <giorno name="' + orario[2][j] + '">' + "\n")
for i in range(3, 12):
lez = orario[i + a*12][j]
if lez == "":
nome_corso_xml.write(' <lezione>' + "-" + '</lezione>' + "\n")
else:
for riga in corso_data:
if riga[0] == lez:
if riga[2] == "":
nome_corso_xml.write(' <lezione name="' + lez + '">' + riga[1] + '</lezione>' + "\n")
else:
for g in range(0, len(riga)):
if riga[g].lower() == orario[2][j].lower():
nome_corso_xml.write(' <lezione name="' + lez + '">' + riga[g+1] + '</lezione>' + "\n")
nome_corso_csv.seek(0)
nome_corso_xml.write(' </giorno>' + "\n")
nome_corso_xml.write(' </anno>' + "\n")
nome_corso_xml.write(' </corso>' + "\n")
nome_corso_xml.write('</orario>' + "\n")
nome_corso_xml.close()
He open the "EDILIZIA.csv" and compile the "EDILIZIA.xml", then he should open the "EDILE-ARCHIT.csv" and compile its xml, but when he read, he keeps on reading from "EDILIZIA.csv"
Here's the .csv files that you need.
http://pastebin.com/kJhL8HpK
If you try to make it read first EDILIZIA.csv and then EDILE-ARCHIT.csv he'll keep on using always the EDILIZIA.csv to compile the xml, but he should firt open EDILIZIA.csv, compile the EDILIZIA.xml, then read the EDILE-ARCHIT.csv and compile the EDILE-ARCHIT.xml.
If you take a look at the final xmls, you'll see that the EDILE-ARCHIT.xml will only display the common subjects of EDILIZIA.csv and EDILE-ARCHIT.csv
It took a long time to figure out what you are doing here. To tell the truth your code is a mess - there are many unused variables and lines that make no sense at all. Anyway, your code reads the appropriate csv file each time, thus the error is not where you thought it was.
If I am right, orario.csv contains the timetable of each course (stored in corsi list) for three semesters or years, and the corso.csv files contain the room where subjects are held. So you want to merge the information into an XML file.
You only forgot one thing: to proceed in orario.csv. Your code wants to merge the very first three anno with the current corso. To fix it, you have to make two changes.
First in this for loop header:
for corso in corsi:
Modify to:
for num, corso in enumerate(corsi):
And when you assign lez:
lez = orario[i + a*12][j]
Modify to:
lez = orario[i + a*12*(num+1)][j]
Now it should work.
This code produces exactly the same result, but it uses Python's XML module to build the output file:
from csv import reader
import xml.etree.cElementTree as ET
import xml.dom.minidom as DOM
corsi = ["EDILIZIA", "EDILE-ARCHIT", "ELETTRONICA", "TECNOLOGIE_DI_INTERNET", "INFORMATICA", "GESTIONALE", "ENERGETICA", "MECCANICA", "CIVILE_ED_AMBIENTALE", "MEDICA", "ENGINEERING_SCIENCES"]
with open('orario.csv', 'r') as orario_csv:
orario = reader(orario_csv)
orario_data = [ row for row in orario ]
for num, corso in enumerate(corsi):
with open(corso + '.csv', 'r') as corso_csv:
corso_raw = reader(corso_csv)
corso_data = [ row for row in corso_raw ]
root_elem = ET.Element('orario')
corso_elem = ET.SubElement(root_elem, 'corso')
corso_elem.set('name', corso)
for anno in range(0, 3):
anno_elem = ET.SubElement(corso_elem, 'anno')
anno_elem.set('num', str(anno + 1))
for giorno in range(1, 6):
giorno_elem = ET.SubElement(anno_elem, 'giorno')
giorno_elem.set('name', orario_data[2][giorno])
for lezione in range(3, 12):
lez = orario_data[lezione + anno * 12 * (num + 1)][giorno]
if lez == '':
lezione_elem = ET.SubElement(giorno_elem, 'lezione')
lezione_elem.text = '-'
else:
for riga in corso_data:
if riga[0] == lez:
if riga[2] == '':
lezione_elem = ET.SubElement(giorno_elem, 'lezione')
lezione_elem.set('name', lez)
lezione_elem.text = riga[1]
else:
for g in range(0, len(riga)):
if riga[g].lower() == orario_data[2][giorno].lower():
lezione_elem = ET.SubElement(giorno_elem, 'lezione')
lezione_elem.set('name', lez)
lezione_elem.text = riga[g + 1]
with open(corso + '_new.xml', 'w') as corso_xml:
xml_data = DOM.parseString(ET.tostring(root_elem, method = 'xml')).toprettyxml(indent = ' ')
corso_xml.write(xml_data)
Cheers.
I think I may have spotted the cause of your problem.
The second item in your corsi list ends with a full stop. This means that you will be looking for the file "EDILE-ARCHIT..csv", which is almost does not exist. When you try and open the file, the open() call will throw an exception, and your program will terminate.
Try removing the trailing full stop, and running it again.