Frozen Python File Can't access "Save_File" - python

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)

Related

I need to write content from f.write to be written in play.txt file. data_file is data from entry box with 8 arguments. KIVY only please

with open('play.txt', 'a+') as data_file:
for i in data_file:
f.write("First game, first court: " + data_file[0] + " and" + data_file[1] + " against " + data_file[2] + " and" + data_file[
3] + ".")
f.write("First game, second court: " + data_file[4] + " and" + data_file[5] + " against " + data_file[6] + " and" + data_file[
7] + ".")
I don't know how to write it in play.txt file*
Thanks for help! <3

Test Run Failed: local variable '' referenced before assignment

Long time reader, first time poster!
I've been working on setting up the first piece of automation at my workplace and teaching myself my first programming language at the same time. The end goal is to set up a Sikuli script to run testing overnight.
I keep running into errors that feel like a lack of understanding on basic python principles and I don't have anyone around to teach me.
The function do_math parses a .csv file, does some math, and returns those variables in a tuple. I then assign those results into a variable and try to compare them but I keep running into:
Test Run Failed: local variable 'D2LAverage' referenced before assignment
I've tried assigning D2LAverage in a number of different places, making it global, returning a list vs tuples, but it just keeps getting stuck.
<handler.py>
def do_math():
with open ('C:/Program Files/TrueVision Surgical/DSM/Logs/Latency_' + timestr + '.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
D2L = []
L2D = []
next(csv_file)
for row in csv_reader:
next
D2L.append(float(row[1]))
L2D.append(float(row[2]))
line_count += 1
else:
D2LAverage = 0
L2DAverage = 0
D2LAverage = float(sum(D2L) / len(D2L))
L2DAverage = float(sum(L2D) / len(L2D))
D2Lvar = sum(pow(x-D2LAverage,2) for x in D2L) / len(D2L) # Get varience
D2Lstd = math.sqrt(D2Lvar) # Calculate STD
L2Dvar = sum(pow(x-L2DAverage,2) for x in L2D) / len(L2D) # Get varience
L2Dstd = math.sqrt(L2Dvar) # Calculate STD
return D2LAverage, D2Lstd, L2DAverage, L2Dstd
<start_script.py> - Calling the above do_math
do_math()
results = do_math()
# Specify the path
path = 'C:/Users/AeosFactory/Desktop/'
# Specify the file name
file_name = "Latency_Results" + "_" + str(datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')) + ".txt"
# Create a file at specified location and do comparison
with open (os.path.join(path, file_name), 'a+') as Latency_Results:
if results[0] <= 85:
Latency_Results.write("Pass" + " - " + "4 Screens, Image Mode 1, Surgery, Live, HC, D2L Average:" + " " + str(round(D2LAverage,2)) + '\n')
else:
Latency_Results.write("Fail" + " - " + "4 Screens, Image Mode 1, Surgery, Live, HC, D2L Average:" + " " + str(round(D2LAverage,2)) + '\n')
if D2Lstd <= 10:
Latency_Results.write("Pass" + " - " + "4 Screens, Image Mode 1, Surgery, Live, HC, D2L Standard Deviation:" + " " + str(round(D2Lstd,2)) + '\n')
else:
Latency_Results.write("Fail" + " - " + "4 Screens, Image Mode 1, Surgery, Live, HC, D2L Standard Deviation:" + " " + str(round(D2Lstd,2)) + '\n')
if L2DAverage <= 85:
Latency_Results.write("Pass" + " - " + "4 Screens, Image Mode 1, Surgery, Live, HC, L2D Average:" + " " + str(round(L2DAverage,2)) + '\n')
else:
Latency_Results.write("Fail" + " - " + "4 Screens, Image Mode 1, Surgery, Live, HC, L2D Average:" + " " + str(round(L2DAverage,2)) + '\n')
if L2Dstd <= 10:
Latency_Results.write("Pass" + " - " + "4 Screens, Image Mode 1, Surgery, Live, HC, L2D Standard Deviation:" + " " + str(round(L2Dstd,2)) + '\n' + '\n')
else:
Latency_Results.write("Fail" + " - " + "4 Screens, Image Mode 1, Surgery, Live, HC, L2D Standard Deviation:" + " " + str(round(L2Dstd,2)) + '\n' + '\n')
With the exception of global variables, variables aren't shared between python files. If you look in start_script.py you never define D2LAverage anywhere. When you attempt to use it during your if statements you raise an error because Python "doesn't know what you're talking about". I think what caught you up is thinking that the name of the values returned is exposed in the scope of where the function was called. All that gets returned is the return value itself.
At the end of do_math() you have the line return D2LAverage, D2Lstd, L2DAverage, L2Dstd, because Python only allows 1 return value per function these get packaged into a tuple.
In start_script.py you call do_math() twice,
once without capturing the return value
once where you assign the return value to results
If you only care about the results of the function, you'll probably want to remove the first call to it.
To access the individual values returned by do_math() you can either access the desired value directly by indexing into the tuple with results[0], or use tuple unpacking to assign the 4 return values to individual variables, with something like D2LAverage, D2Lstd, L2DAverage, L2Dstd = results.

How to put together datas into a file?

I would like to collect different type of datas into a file. Here is a part of the code.
val = str(float(data[-1]))
val_dB = float(val)
val_dB = math.log(val_dB, 10) * 10
myfile = open('../../../MLI_values/mli_value.txt', 'a')
myfile.write(date_ID + " " + val + val_dB + "\n")
myfile.close()
But it gives back an error:
myfile.write(date_ID + " " + val + val_dB + "\n")
TypeError: cannot concatenate 'str' and 'float' objects
How can I solve it to put them together? (into columns) into a file?
Change:
myfile.write(date_ID + " " + val + val_dB + "\n")
to:
myfile.write(date_ID + " " + val + " " + str(val_dB) + "\n")

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 ?

Python Nested Loop Fails

I am writing a program to perform file integrity checks of files in a directory. There are 3 nested loops in the code. When I run the code, the first two loops work great but the third loop does not run more than once.
import hashlib
import logging as log
import optparse
import os
import re
import sys
import glob
import shutil
def md5(fileName):
"""Compute md5 hash of the specified file"""
try:
fileHandle = open(fileName, "rb")
except IOError:
return
m5Hash = hashlib.md5()
while True:
data = fileHandle.read(8192)
if not data:
break
m5Hash.update(data)
fileHandle.close()
return m5Hash.hexdigest()
req = open("requested.txt")
for reqline in req:
reqName = reqline[reqline.rfind('/') + 1:len(reqline) - 1]
reqDir = reqline[0:reqline.rfind('/') + 1]
ezfimlog = open("ezfimlog.txt", 'a')
actFile = open("activefile.txt")
tempFile = open("activetemp.txt", 'w')
for name in glob.glob(reqDir + reqName):
fileHash = md5(name)
actInt = 0
if fileHash != None:
print fileHash
for actLine in actFile:
actNameDir = actLine[0:actLine.rfind(' : ')]
actHash = actLine[actLine.rfind(' : ') + 3:len(actLine) -1]
print (name + " " + actHash + " " + fileHash)
if actNameDir == name and actHash == fileHash:
tempFile.write(name + " : " + fileHash + "\n")
actInt = 1
if actNameDir == name and actHash != fileHash:
tempFile.write(name + " : " + actHash + "\n")
actInt = 1
ezfimlog.write("EzFIM Log: The file " + name + " was modified: " + actHash + "\n")
if actInt == 0:
ezfimlog.write("EzFIM Log: The file " + name + " was created: " + fileHash + "\n")
tempFile.write(name + " : " + fileHash + "\n")
shutil.copyfile("activetemp.txt", "activefile.txt")
You open actFile once and then try to read it many times. You'll need to open it each time you want to read it.
Move this line:
actFile = open("activefile.txt")
to just before this line:
for actLine in actFile:

Categories