How to align two columns perfectly in python? - python

I have an assignment where we have to read the file we created that has the test names and scores and print them in columns. Getting the data and displaying it, along with the average, is no problem, but I do not understand how to align the scores to the right in the output column. In the output example the scores line up perfectly to the right of the "SCORES" column. I can format their width using format(scores, '10d') as an example, but that's always relative to how long the name of the test was. Any advice?
def main():
testAndscores = open('tests.txt', 'r')
totalTestscoresVaule = 0
numberOfexams = 0
line = testAndscores.readline()
print("Reading tests and scores")
print("============================")
print("TEST SCORES")
while line != "":
examName = line.rstrip('\n')
testScore = float(testAndscores.readline())
totalTestscoresVaule += testScore
## here is where I am having problems
## can't seem to find info how to align into
## two columns.
print(format(examName),end="")
print(format(" "),end="")
print(repr(testScore).ljust(20))
line = testAndscores.readline()
numberOfexams += 1
averageOftheTestscores = totalTestscoresVaule / numberOfexams
print("Average is", (averageOftheTestscores))
#close the file
testAndscores.close()
main()

You just have to store each name and score in a list, then calculate the longest name, and use this length to print space for shorter name.
def main():
with open('tests.txt', 'r') as f:
data = []
totalTestscoresVaule = 0
numberOfexams = 0
while True:
exam_name = f.readline().rstrip('\n')
if exam_name == "":
break
line = f.readline().rstrip('\n')
test_score = float(line)
totalTestscoresVaule += test_score
data.append({'name': exam_name, 'score': test_score})
numberOfexams += 1
averageOftheTestscores = totalTestscoresVaule / numberOfexams
longuest_test_name = max([len(d['name']) for d in data])
print("Reading tests and scores")
print("============================")
print("TEST{0} SCORES".format(' ' * (longuest_test_name - 4)))
for d in data:
print(format(d['name']), end=" ")
print(format(" " * (longuest_test_name - len(d['name']))), end="")
print(repr(d['score']).ljust(20))
print("Average is", (averageOftheTestscores))
main()

Related

While reading a text file sequentially how to go back to a particular line and start again from there

Newbie alert!
Path = "C:/Users/Kailash/Downloads/Results_For_Stride-Table.csv"
counter_start = 0
counter_end = 0
num_lines = len(open(Path).read().splitlines())
print("num_lines = ", num_lines)
with open(Path, "r") as f:
for lines in f:
print("lines = ", lines)
counter_end += 1
Stride_Length = lines.split(", ")
Previous_Sum = distances
Previous_Sum_GCT = Total_GCT
Previous_Heading = Sum_Heading
GCT = float(Stride_Length[2])
Total_GCT += GCT
print("Total_GCT = ", Total_GCT)
distances += float(Stride_Length[3])
print("distances = ", distances)
Sum_Heading += float(Stride_Length[7])
print("Sum_Heading = ", Sum_Heading)
print("counter_end = ", counter_end)
if(GCT == 0.00):
distances = 0
counter_end = 0
if distances > 762:
print("counter_end = ", counter_end)
counter_start = counter_end
lines_test = f.readlines()
print("counter start = ", counter_start)
print("move = ", lines_test[counter_start-counter_end-1])
print("Distance is above 762")
distances = 0
I want to know how to go back to a particular line in a file and start reading from there again in python. when I try to use f.readlines() in the last but 5th line in my code, the processing stops right there.
You can build a list of line start positions (file offsets), and then use file.seek(line_offsets[n]) to go back to the nth line (counting from zero). After that you can read the line (and those following it sequentially) once again.
Here's example code showing building such a list incrementally:
filepath = "somefile"
line_offsets = []
with open(filepath, "r") as file:
while True:
posn = file.tell()
line = file.readline()
if not line: # end-of-file?
break
line_offsets.append(posn) # Remember where line started.
""" Process line """
... code above ...
for line in data:
if counter_end<= <line to stop at>:
continue
counter_end += 1
...
a = linecache.getlines('D:/aaa.txt')[5]
import linecache
a = linecache.getlines('D:/aaa.txt')[5]

In python how do i sort a txt file in ascending order

so i have written this code so far to sort a log.txt file into a leaderboard.txt in descending order. But i now want it in ascending order. How do I do that. Heres the file:
def extract_log_info(log_file = "log.txt"):
with open(log_file, 'r') as log_info:
new_name, new_score = [i.strip('\n') for i in
log_info.readlines()[:2]]
new_score = int(new_score)
return new_name, new_score
def update_leaderboards(new_name, new_score, lb_file =
"Leaderboards.txt"):
cur_index = None
with open(lb_file, 'r') as lb_info:
lb_lines = lb_info.readlines()
lb_lines_cp = list(lb_lines) # Make a copy for iterating over
for line in lb_lines_cp:
if 'Leaderboards' in line or line == '\n':
continue
# Now we're at the numbers
position, name, score = [ i for i in line.split() ]
if new_score > int(score):
cur_index = lb_lines.index(line)
cur_place = int(position.strip(')'))
break
# If you have reached the bottom of the leaderboard, and there
# are no scores lower than yours
if cur_index is None:
# last_place essentially gets the number of entries thus far
last_place = int(lb_lines[-1].split()[0].strip(')'))
entry = "{}) {}\t{}\n".format((last_place+1), new_name,
new_score)
lb_lines.append(entry)
else: # You've found a score you've beaten
entry = "{}) {}\t{}\n".format(cur_place, new_name, new_score)
lb_lines.insert(cur_index, entry)
lb_lines_cp = list(lb_lines) # Make a copy for iterating over
for line in lb_lines_cp[cur_index+1:]:
position, entry_info = line.split(')', 1)
new_entry_info = str(int(position)+1) + ')' + entry_info
lb_lines[lb_lines.index(line)] = new_entry_info
with open(lb_file, 'w') as lb_file_o:
lb_file_o.writelines(lb_lines)
if __name__ == '__main__':
name, score = extract_log_info()
update_leaderboards(name, score)
the reason i want it in ascending order is because the game im getting the scores
If you've already written the file in descending order, just do this:
with open('ascending_file.txt', 'r') as ascend:
lines = ascend.readlines()
with open('descending_file.txt' 'w') as descend:
ascend.reverse():
descend.writelines(ascend)

adding simple mathematical operation to python script

I have a program that operates on a csv file to create output that looks like this:
724, 2
724, 1
725, 3
725, 3
726, 1
726, 0
I would like to modify the script with some simple math operations such that it would render the output:
724, 1.5
725, 3
726, 0.5
The script I'm currently using is here:
lines=open("1.txt",'r').read().splitlines()
for l in lines:
data = l.split('"Overall evaluation:')
if len(data) == 2:
print(data[0] + ", " + data[1])
How could I add a simple averaging and slicing operation to that pipeline?
I guess I need to create some temporary variable, but it should be outside the loop that iterates over lines?
Maybe something like this:
lines=open("EasyChairData.csv",'r').read().splitlines()
for l in lines:
data = l.split('"Overall evaluation:')
submission_number_repo = data[0]
if len(data) == 2:
print(data[0] + ", " + data[1])
if submission_number_repo != data[0]
submission_number_repo = data[0]
EDIT
The function is just a simple average
You can use a dictionary that map the key to the total and count and then print it:
map = {}
lines=open("1.txt",'r').read().splitlines()
for l in lines:
data = l.split('"Overall evaluation:')
if len(data) == 2:
if data[0] not in map.keys():
map[data[0]] = (0,0)
map[data[0]] = (map[data[0]][0]+int(data[1]) , map[data[0]][1]+1)
for x, y in map.items():
print(str(x) + ", " + str(y[0]/y[1]))
I would just store an list of values with the key. Then take the average when file is read.
lines=open("1.txt",'r').read().splitlines()
results = {}
for l in lines:
data = l.split('"Overall evaluation:')
if len(data) == 2:
if data[0] in results:
results[data[0]].append(data[1])
else:
results[data[0]] = [data[1]]
for k,v in results.iteritems():
print("{} , {}".format(k, sum(v)/len(v) ))
A simple way is to keep a state storing current number, current sum and number of items, and only print it when current number changes (do not forget to print last state!). Code could be:
lines=open("1.txt",'r') # .read().splitlines() is useless and only force a full load in memory
state = [None]
for l in lines:
data = l.split('"Overall evaluation:')
if len(data) == 2:
if data[0] != state[0]:
if state[0] is not None:
average = state[1]/state[2]
print(state[0] + ", " + str(average))
state = [data[0], 0., 0]
state[1] += float(data[1])
state[2] += 1
if state[0] is not None:
average = state[1]/state[2]
print(data[0] + ", " + str(average))
(Edited to avoid storing of values)
I love defaultdict:
from collections import defaultdict
average = defaultdict(lambda: (0,0))
with open("1.txt") as input:
for line in input.readlines():
data = line.split('"Overall evaluation:')
if len(data) != 2:
continue
key = data[0].strip()
val = float(data[1])
average[key] = (val+average[key][0], average[key][1]+1)
for k in sorted(average):
v = average[k]
print "{},{}".format(k, v[0]/v[1])

Opening a file for append error

I'm trying to open a file for appending, but I keep getting the "except" portion of my try/except block, meaning there is some sort of error with the code but I can't seem to find what exactly is wrong with it. It only happens when I try to open a new file like so:
results = open("results.txt", "a")
results.append(score3)
Here's my full code:
import statistics
# input
filename = input("Enter a class to grade: ")
try:
# open file name
open(filename+".txt", "r")
print("Succesfully opened", filename,".txt", sep='')
print("**** ANALYZING ****")
with open(filename+".txt", 'r') as f:
counter1 = 0
counter2 = 0
right = 0
answerkey = "B,A,D,D,C,B,D,A,C,C,D,B,A,B,A,C,B,D,A,C,A,A,B,D,D"
a = []
# validating files
for line in f:
if len(line.split(',')) !=26:
print("Invalid line of data: does not contain exactly 26 values:")
print(line)
counter2 += 1
counter1 -= 1
if line.split(",")[0][1:9].isdigit() != True:
print("Invalid line of data: wrong N#:")
print(line)
counter2 += 1
counter1 -= 1
if len(line.split(",")[0]) != 9:
print("Invalid line of data: wrong N#:")
print(line)
counter2 += 1
counter1 -= 1
counter1 += 1
#grading students
score = len(([x for x in zip(answerkey.split(","), line.split(",")[1:]) if x[0] != x[1]]))
score1 = 26 - score
score2 = score1 / 26
score3 = score2 * 100
a.append(score3)
# results file
results = open("results.txt", "a")
results.write(score3)
# in case of no errors
if counter2 == 0:
print("No errors found!")
# calculating
number = len(a)
sum1 = sum(a)
max1 = max(a)
min1 = min(a)
range1 = max1 - min1
av = sum1/number
# turn to int
av1 = int(av)
max2 = int(max1)
min2 = int(min1)
range2 = int(range1)
# median
sort1 = sorted(a)
number2 = number / 2
number2i = int(number2)
median = a[number2i]
median1 = int(median)
# mode
from statistics import mode
mode = mode(sort1)
imode = int(mode)
# printing
print ("**** REPORT ****")
print ("Total valid lines of data:", counter1)
print ("Total invalid lines of data:", counter2)
print ("Mean (average) score:", av1)
print ("Highest score:", max2)
print("Lowest score:", min2)
print("Range of scores:", range2)
print("Median Score:", median1)
print("Mode score(s):", imode)
results.close()
except:
print("File cannot be found.")
I don't think there is a method called append for writing into file. You can use the write or writelines method only to write. As you already opened the file with append permissions. It wont change the old data and will append the text to the file.
f=open('ccc.txt','a')
f.write('Hellloooo')
f.close()
Hope it helps.

Find Min and Max from Text File - Python

I need to find the minimum and max value from this list of data. I can get the maximum but the minimum. The text file has a lot of data so I decided to upload it here: https://www.dropbox.com/s/u5ov5zij9v5fumt/project05.data.txt?dl=0
Input
try:
file_name = input("Enter the name of an input file ")
input_file = open( file_name, "r" )
header=input_file.readline()
count=0
total=0
largest_num=0
smallest_num=0
michigan=""
for line in input_file:
output=float(line[67:71].rstrip())
total += output
count +=1
if largest_num<= output:
largest_num = output
if smallest_num >= output:
smallest_num = output
if line[0:17].rstrip() == "Michigan":
state=(line[0:17])
number=(line[67:75])
print("\nState with the smallest MMR vaccation rate:")
print(" with a rate of")
print("\n State with largest MMR vaccination rate:" )
print(" with a rate of")
print("\nThe calculated average vaccination rate is",round(total/count,1))
print("")
print("Michigan MMR vaccination rate is", number)
input_file.close()
except FileNotFoundError:
print("Error: file not found")
file_name = input("Enter the name of an input file ")
input_file = open( file_name, "r" )
List comprehensions are your friends.
numbers = [float(line[67:71].rstrip()) for line in input_file]
largest_num = max(numbers)
smallest_num = min(numbers)
total = sum(numbers)
count = len(numbers)

Categories

Resources