Making A Statistics Text File (Python) - python

I'm making a program that takes a name and certain input in the form of numbers and gives them a score i want this score to be saved in a text file and i want to be able to do it multiple times but when I write to the file it overwrites the last stat is there anyway to change this
Here is the function I'm using:
def calculate():
try:
a = float(enter1.get())
b = float(enter2.get())
c = float(enter3.get())
d = float(enter4.get())
e = float(enter5.get())
f = float(enter6.get())
result =(a+b+(c*2)+(d*2)+e-f)*2.5
n = result
w = "Score:"
label7.config(text=str(result))
myfile = open('Stats.txt','w')
x = str(enter0.get())
y =("(%s) %s" % (w, n))
myfile.write(x)
myfile.write(y)
myfile.close()
except ValueError:
label7.config(text='Enter Numbers!',fg="white")

Maybe change
myfile = open('Stats.txt','w')
into
myfile = open('Stats.txt','a') # append

Related

Dynamic save to csv using arrays

I'm using the csv module to save arrays to csv, however I want to make it abit more dynamic. Apologies if this is already up here, I tried searching but to no avail.
this is my current code, it works well....
filename = 'zeroTime_.csv' #save to csv
f = open(filename, "w")
f.write("{},{},{},{}\n".format("R[0]", "F[0]","R[1]", "F[1]"))
for x in zip(R[0], F[0],R[1], F[1]):
f.write("{},{},{},{}\n".format(x[0], x[1], x[2], x[3]))
f.close()
However I want to make it so that if array R has more than 2 columns in, it will still work
I tried creating the "R[0]", "F[0]","R[1]", "F[1]" as a string and just using that but it doesnt like it, my code creates a R and F for each channel denoted by NumCh:
for x in range(NumCh):
title = title +'"R['+str(x)+']",'+'"F['+str(x)+']",'
bracket = bracket + '{},{},'
title = title[:-1]
bracket = bracket[:-1]
bracket = bracket + '\n"'
filename = 'zeroTime_.csv' #save to csv
f = open(filename, "w")
f.write(bracket.format(title))
for x in zip(R[0], F[0],R[1], F[1]):
f.write(bracket.format(x[0], x[1], x[2], x[3]))
f.close()
Gives me the error:
Traceback (most recent call last):
File "base.py", line 8, in <module>
b = pd.proc(NumCh, a)
File "C:\Users\jtpkalaverick\Documents\Python\module\time_proc.py", line 24, in proc
f.write(bracket.format(title))
IndexError: Replacement index 1 out of range for positional args tuple
(I'm running this within a module addressed as pd.)
edit (30.06.22)
i have 2 modules tick_proc that produces some arbitrary arrays and time_proc that does some basic maths on the arrays. NumCh and samples are passed into the modules and are just ints
main code:
import tick_proc as tp
import time_proc as pd
NumCh = 2
samples = 10
a = tp.collect_data(NumCh, samples)
b = pd.proc(NumCh, a)
print('b', b)
tick proc:
print('Importing module "TickProc"')
R = []
F = []
def collect_data(NumCh, samples):
for x in range(NumCh):
R.append([])
F.append([])
for x in range(NumCh):
for y in range(samples):
R[x].append(y*x)
F[x].append(y*x -1)
return F, R
time_proc:
import csv
def proc(NumCh, a):
R = a[0]
F = a[1]
T = []
bracket = '"'
title = ''
vars = ''
for x in range(NumCh):
T.append([])
title = title +'"R['+str(x)+']",'+'"F['+str(x)+']",'
bracket = bracket + '{},{},'
title = title[:-1]
bracket = bracket[:-1]
bracket = bracket + '\n"'
print(bracket)
print(title)
for i in range(NumCh):
for j in range(len(R[i])):
T[i].append(R[i][j]-F[i][j])
filename = 'zeroTime_.csv' #save to csv
f = open(filename, "w")
f.write(bracket.format(title))
for x in zip(R[0], F[0],R[1], F[1]):
f.write(bracket.format(x[0], x[1], x[2], x[3]))
f.close()
return T

Reading through a list in a txt file and output each value in the list to a new txt file python

So I have a script which essentially compares values and then output a report with the final values. It outputs them in to a list which is not what I want. Ideally i want to be able to have each value on a separate line one by one. So far my code is as follows :
def readIntoList(path):
with open(path, "r") as text1:
lines = text1.readlines()
result = []
for l in lines:
l_list = l.replace("\n", "").split(" ")
result.extend(l_list)
return result
def Diff(li1, li2):
f = open("final-output.txt", "w")
f.write(str(list(set(li2) - set(li1))))
if __name__ == '__main__':
a = readIntoList('file2.txt')
b = readIntoList('file3.txt')
result = Diff(a, b)
The function Diff is what outputs the following in final-output.txt :
['07577930503', '07577930502', '07577930500', '07577985801']
I want each number to be on a single line
You can change your "Diff" function code to:
def Diff(li1, li2):
f = open("final-output.txt", "w")
listOfValues = list(set(li2) - set(li1))
for value in listOfValues:
f.write(str(value) + "\n")

Am trying to get the average of a list from a text file

This the link to see the image of the text file I need help with feature one, click here to see the imageFor some reason when I print out the average of the list, it only shows the number from the text file. I don't know where my mistake is. I think the issue might be when am appending the list.
f = open("votes.txt")
lines = f.read().split('\n')
issueA = {}
voteAa = {}
voteBa = {}
while(True):
for line in lines:
col = line.split(' ')
issue = col[0]
voteA = float(col[1])
voteB = float(col[2])
if voteA in voteAa:
voteAa[issue].append(voteA)
else:
voteAa[issue] = [voteA]
if voteB in voteBa:
voteBa[issue].append(voteB)
else:
voteBa[issue] = [voteB]
choice = int(input("Which choice? "))
if choice == 1:
for issue in voteAa:
sumVote = sum(voteAa[issue])
avg = sumVote / len(voteAa[issue])
print("avg is ",sumVote)
how about this
f = open("votes.txt")
lines = f.read().split('\n')
issues = []
voteAa = []
voteBa = []
for line in lines:
col = line.split(' ')
issue = col[0]
voteA = float(col[1])
voteB = float(col[2])
issues.append(issue)
voteAa.append(voteA)
voteBa.append(voteB)
avgA = voteAa.count(0)/len(issues) * 1.0
avgB = voteBa.count(0)/len(issues) * 1.0
if (avgA > avgB):
print('B higher than A'
elif (avgB > avbA):
print('A higher than B')
Since you need average by issue
remove for issue loop
and compute average in one line with special mean function like below
avg = mean(voteAa.values())
or, if you prefer keep it close to your code
sumVote = sum(voteAa.values())
avg = sumVote / len(voteAa)
also correct print line to
print("avg is ", avg)
Also you should just collect votes not need for if in the first loop.
So resulting script is
f = open("votes.txt")
lines = f.read().split('\n')
issueA = {}
voteAa = {}
voteBa = {}
for line in lines:
col = line.split()
issue = col[0]
voteA = float(col[1])
voteB = float(col[2])
voteAa[issue] = voteA
sumVote = sum(voteAa.values())
avg = sumVote / len(voteAa)
print("avg is ", avg)
I tried to keep close to your original code, and did not say replace dictionaries with arrays, it could be simplified even further if you like, say with pandas or even standard https://docs.python.org/3/library/csv.html

Copy 'N' lines from one file to another in python?

Essentially what I am attempting to do is read 'n' number of lines from a file and then write them to a separate file. This program essentially should take a file that has 100 lines and separate that file into 50 separate files.
def main():
from itertools import islice
userfile = raw_input("Please enter the file you wish to open\n(must be in this directory): ")
file1 = open(userfile, "r+")
#print "Name: ", file1.name
#print "Closed or not", file1.closed
#print "Opening mode: ", file1.mode
#print "Softspace flag: ", file1.softspace
jcardtop = file1.read(221);
#print jcardtop
n = 2
count = 0
while True:
next_n_lines = list(islice(file1,n))
print next_n_lines
count = count + 1
fileout = open(str(count)+ ".txt", "w+")
fileout.write(str(jcardtop))
fileout.write(str(next_n_lines))
fileout.close()
break
if not next_n_lines:
break
I do have the file printing as well to show what is in the variable next_n_lines.
*['\n', "randomtext' more junk here\n"]
I would like it instead to look like
randomtext' more junk here
Is this a limitatoin of the islice function? Or am I missing a portion of the syntax?
Thanks for your time!
Where you call str() or print, you want to ''.join(next_n_lines) instead:
print ''.join(next_n_lines)
and
fileout.write(''.join(next_n_lines))
You can store the flattened string in a variable if you don't want to call join twice.
Did you mean something like this?
f = open(userfile,"r")
start = 4
n_lines = 100
for line in f.readlines()[start:(start + n_lines)]:
print line
#do stuff with line
or maybe this rough, yet effective code:
f = open(userfile,"r")
start = 4
end = start + 100
count = start
while count != end:
for line in f.readlines()[count:(count + 2)]:
fileout = open(str(count)+ ".txt", "w+")
fileout.write(str(line))
fileout.close()
count = count + 2

Making columns of data lists in python

So I have a program, that reads through a bunch of files and appends the necessary data that I need. I need to now take those particular data and show them as a list. To be more specific, these are the parameters I have:
a = Source, b = luminosity, c = luminosity error, d = HST, e = XRS, f = gmag, g = z, and h = rh
I want to display this in a list, each defining a particular column. I just don't know where exactly I should insert the print statement among the various for loops I've done to do this.
I would appreciate any help! Here's the program (the main focus is in the for loops done and how they iterate through the data, and don't worry about indentations, the program so far works I just need to display the data appended in columns):
import sys
import os
import re
import urllib
import urllib2
from os.path import basename
import urlparse
import shutil
base_dirname = '/projects/XRB_Web/apmanuel/499/'
base_sourcefile = base_dirname + 'Sources.txt'
try:
file = open(base_sourcefile, 'r')
except IOError:
print 'Cannot open: '+base_sourcefile
Source = []
Finallist = []
ACS = []
SRC = []
for line in file:
data_line_check = (line.strip())
if data_line_check:
line = re.sub(r'\s+', ' ', line)
point = line.split('|')
temp_source = (point[0]).strip()
if temp_source and len(point) == 3:
Source = (point[0]).strip()
Source = re.sub(r'\s', '_', Source)
print Source+"\n"
temp_finallist = (point[1]).strip()
if temp_finallist:
Finallistaddress = (point[1]).strip()
Finallistaddress = re.sub(r'\s', '_', Finallistaddress)
Luminositybase_dirname1 = '/projects/XRB_Web/apmanuel/499/Lists/' + Finallistaddress
try:
file2 = open(Luminositybase_dirname1, 'r')
except IOError:
print 'Cannot open: '+Luminositybase_dirname1
source = []
luminosity = []
luminosityerr = []
for line in file2:
pointy = line.split()
a = int(pointy[0])
b = float(pointy[5])
c = float(pointy[6])
source.append(a)
luminosity.append(b)
luminosityerr.append(c)
temp_HST = (point[2]).strip()
if temp_HST:
HSTaddress = (point[2]).strip()
HSTaddress = re.sub(r'\s', '_', HSTaddress)
HSTbase_dirname2 = '/projects/XRB_Web/apmanuel/499/Lists/' + HSTaddress
try:
file3 = open(HSTbase_dirname2, 'r')
except IOError:
print 'Cannot open: '+HSTbase_dirname2
HST = []
for line in file3:
pointy2 = line.split()
d = int(pointy2[0])
HST.append(d)
temp_XRS = (point[3]).strip()
if temp_XRS:
XRSaddress = (point[3]).strip()
XRSaddress =re.sub(r'\s', '_', XRSaddress)
XRSbase_dirname3 = '/projects/XRB_Web/apmanuel/499/Lists/' + XRSaddress
try:
file4 = open(XRSbase_dirname3, 'r')
except IOError:
print 'Cannot open: '+XRSbase_dirname3
XRS = []
for line in file4:
pointy3 = line.split()
e = int(pointy3[0])
XRS.append(e)
temp_others = (point[4]).strip()
if temp_others:
othersaddress = (point[4]).strip()
othersaddress =re.sub(r'\s', '_', othersaddress)
othersbase_dirname4 = '/projects/XRB_Web/apmanuel/499/Lists/' + othersaddress
try:
file5 = open(othersbase_dirname4, 'r')
except IOError:
print 'Cannot open: '+othersbase_dirname4
gmag = []
z = []
rh = []
for line in file5:
pointy4 = line.split()
f = float(pointy4[3])
g = float(pointy4[5])
h = float(pointy4[7])
rh.append(f)
gmag.append(g)
z.append(h)
this function will return columns for a list of rows. note that this requires the lists to all have an element in the column you are trying to access, though it would be relatively simple to change this if you need it.
def getcolumn(matrix,index): #index specifies which column of the matrix you want. note that like all other list indexes, this starts from 0, not one.
column = []
for row in matrix:
column.append(row[index])
return column

Categories