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
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.
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")
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 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: