I have to read a list of 12 grades from a text file. Each grade is on a new line in the text file. I have to find the lowest grade and drop it(in the text file as well), then find the average score of the grades. I am having trouble making the text values into integer values so I can find the average. I also can't figure out how to find the lowest grade and drop it.
Here is my code:
try:
homeworkFile = open('homework.txt', 'r')
except:
print("Error: invalid file")
else:
lines = homeworkFile.readlines()
homeworkFile.close()
homeworkFile = open('homework.txt', 'w')
for line in lines:
Thanks for any help you can give!
So this is just one way to take all of your values and calculate the average.
input_file = input("enter file name: ")
open_file = open(input_file, 'r')
Here I just put all of your values into notepad and read through it
grades_list = []
for grade in open_file:
grade_format = grade.strip() #how to remove extra blank space
grades_list.append(grade_format)
Then I used a for-loop to go through each line and put the grades into a list
grade_convert = [] #new list for all of the converted values
for grade in grades_list:
convert = float(grade) #convert each value in the list into a float
grade_convert.append(convert)
I used another list for converted each value
grade_convert = sorted(grade_convert) #very first element will be the lowest
grade_convert.pop(0) #permanently removes the very first item
grade_total = 0 #set a counter
for grade in grade_convert:
grade_total += grade #add all of the values to the counter
grade_average = grade_total / len(grade_convert) #len is number of items
print(grade_average)
grades_list = []
for line in lines :`
grade = float(line)
grades_list.append(grade)
grades_list.sort()
lowest_grade = grades_list[0] #There is the lowest grade
This is one way you can structure your logic. You need to convert values to float pre-processing. Using with is recommended instead of using open and close explicitly.
import os
file = 'homework.txt'
# check if file exists
assert os.path.exists(file), "File does not exist: {0}".format(file)
# use with to open/close file implicitly
with open(mystr, 'w') as file_in:
lines = homeworkFile.readlines()
grades = sorted(float(line) for line in lines)
# drop lowest trade
del grades[0]
Related
I'm trying to create a highscore file in Python 3.1 that stores (already declared) username with scores. Then, I want the program to print the top 5 scores and the users that achieved them.
Currently, I'm using two files - highscores.txt and highuser.txt. What I want is for the code to find the highest integer value in highscores.txt, take its array and match it to the same position in highuser.txt.
Here's my current code:
def highscores():
global score
highscores = open("highscores.txt", "a")
highscores.write(str(score))
highscores.write("\n")
print("done")
highscoreuser = open("highuser.txt", "a")
global username
highscoreuser.write(username)
highscoreuser.write("\n")
print("done")
This code works, but I don't know how to sort the files.
this should do it
with open('highscores.txt','r') as infile:
maxval = 0
maxline = None
i = 0
for line in infile:
if maxval<int(line):
maxline = i
maxval = int(line)
i+=1
i = 0
with open('highuser.txt','r') as infile:
for line in infile:
if i == maxline:
highuser = line.strip()
break
i+=1
Try this:
https://www.geeksforgeeks.org/python-program-to-find-n-largest-elements-from-a-list/
Just use it for 5.
Also make sure to close your files. highscores.close()
And reopen them to read. highscores = highscores.open("highscores.txt", "r")
Make an array of all highscores by .split("\n")
Then similarly create a array of all users by .split("\n")
For each of the top 5 scores search the array for that score and get the indexes.
Then plug in those indexes into the user array and get the resulting users.
You could also make a dictionary with each user and their score and just find the 5 highest scores from all the users.
I am trying to count up unique names that start with "From:" from a file name. However, I keep getting a long list of numbers. What is my code actually reading and how do I fix this?
count = 0
name = []
fname = input("What is your file name? Enter it here: ")
try:
fname = open(fname)
name = set(f.readlines())
except:
print ("That file does not exist.")
for name in fname:
if name.startswith("From:"):
count = len(name)
print (count)
We can make use of set to hold all required names and find its length to get the count:
file_name = input("What is your file name? Enter it here: ")
s = set()
with open(file_name) as f:
for name in f:
if name.startswith('From:'):
s.add(name)
print(len(s))
Try this:
words = []
count = 0
with open ("unique.txt","r") as f:
# Get a list of lines in the file and covert it into a set
words = set(f.readlines())
FromWords=[]
for word in words:
if word.startswith("From:"):
FromWords.append(word)
print(len(FromWords))
First, we filter out all duplicate words and then look for the words which start with From: and this may aid in faster processing if you're dealing with the big amount of data.
let me know if you need any help in this regard.
Input:txt file
iam working with file contains lot of data and i have to get some numbers after specified sentence then calc avrg of these number
# Use the file name mbox-short.txt as the file name
count = 0
fname = raw_input("Enter file name: ")
fh = open(fname)
for lines in fh:
if lines.startswith ("X-DSPAM-Confidence:"):
lines = float (lines [20:50])
count = count +1
print lines
print count
what i get from here is
0.8475
0.6178
0.6961
0.7565
0.7626
0.7556
0.7002
0.7615
0.7601
0.7605
0.6959
0.7606
0.7559
0.7605
0.6932
0.7558
0.6526
0.6948
0.6528
0.7002
0.7554
0.6956
0.6959
0.7556
0.9846
0.8509
0.9907
that loop get to lines start with that txt "X-DSPAM-Confidence:"
and strip it from 20:50 (end of it)
then get me to 2 things get the list of numbers needed and the count which will help later, now i need to sum number to calc avrg. the sum / count
how can i do that? looking for simplest way ever not a problem if i get long code
well i just improved code removed unwanted things sorry for that
print things not important but just to see what i am doing as i am a new to python
using your own code just keep track of the total and divide at the end:
count = 0
total = 0
fname = raw_input("Enter file name: ")
fh = open(fname)
for lines in fh:
if lines.startswith ("X-DSPAM-Confidence:"):
count += 1
total += float (lines [20:50])
print lines
print count
print(total/count)
If you need to store all the data then a list comp would be the best approach to store all the floats then sum and divide the length to get the average:
fname = raw_input("Enter file name: ")
with open(fname) as f:
all_data = [float(line[20:50]) for line in f if line.startswith ("X-DSPAM-Confidence:")]
avg = sum(all_data) / len(all_data)
print(all_data)
print(avg)
It would help if we saw a sample of your data, but you should be able to do this:
sum_lines = sum(lines)
avg_lines = sum_lines / count
sum() is a built in function which will sum an iterable.
I am also wondering why you are reassigning your value to lines when you do
lines = float (lines [20:50])
I would think if those are multiple comma separated floating point numbers, you would want to assign it to a list variable like float_list and then sum using the sum() function.
If you do not want to save the average, you could put a third print that says
print sum(float_list) / count
Updated to Reflect OP Update
Yes you definitely want to create a list. instead of lines = float (lines [20:50]) do this:
float_list = []
float_list = float(line[20:50])
A better way to do this would be to do it with list comprehension.
float_list = [float(lines[20:50] for lines in fh if lines.startwith("X-DSPAM-Confidence:")]
Update...
I think that I misunderstood your original use of the slice [20:50] as representing multiple numbers per line.
If it is only one number, then it would be this, which is basically the answer that Padraic Cunningham posted:
# Use the file name mbox-short.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
float_list = [float(lines[20:50] for lines in fh if lines.startwith("X-DSPAM-Confidence:")]
list_sum = sum(float_list)
count = len(float_list)
list_avg = list_sum / count
For future reference, it is helpful to post an example of your input data along with your code and desired output in your original question.
Depends mostly on the formatting of your numbers, are they CSV, are they on their own line etc. In any case, a general solution:
As some of the comments have pointed out, your first loop will ruin your iterator, so I combined the two loops. The if else is redundant as if not will work fine.
count = 0
sum = 0
fname = raw_input("Enter file name: ")
fh = open(fname,'r')
lines = fh.readlines()
fh.close()
for line in lines:
if line.startswith ("X-DSPAM-Confidence:"):
continue
else:
line = float(line)
count = count +1
sum += line
avg = sum/count
print avg
I have a .txt file that has the following information in it that displays a users name and then 3 scores that they have scored in a quiz:
callum,10,7,9
carl,10,10,10
hollie,1,4,7
brad,4,8,3
kyle,7,2,0
I would like to sort it into alphabetical order displaying the users highest score after their name.
Read file content.
Use readlines() method to read lines from file.
Use split() to get Name and score.
Add in dictionary: Name is Key and Value is total score.
Get all keys from the result dictionary.
User sort() method to sort list by alphabets.
Print result by alphabets order.
Code
p = "/home/vivek/Desktop/test_input.txt"
result = {}
with open(p, "rb") as fp:
for i in fp.readlines():
tmp = i.split(",")
try:
result[(tmp[0])] = eval(tmp[1]) + eval(tmp[2]) + eval(tmp[3])
except:
pass
alphabetical_name = result.keys()
alphabetical_name.sort()
for i in alphabetical_name:
print "Name:%s, Highest score: %d"%(i, result[i])
Output:
$ python test.py
Name:brad, Highest score: 15
Name:callum, Highest score: 26
Name:carl, Highest score: 30
Name:hollie, Highest score: 12
Name:kyle, Highest score: 9
So i would first of all isolate all the lines:
with open('filename') as f:
lines = f.readlines()
So i will continue assuming I have a list called lines with the following content:
lines = ["callum,10,7,9","carl,10,10,10","hollie,1,4,7","brad,4,8,3","kyle,7,2,0"]
Then I will firstly sort the line by name
lines = sorted(lines)
Then for each line you want to isolate the marks, sort them and print them back:
for line in lines:
#name is what there is before the first comma
name = line[:line.find(",")]
#marks are what there is after the second comma and are comma separated
marks = line[line.find(",")+1:].split(",")
#sort the marks
marks = sorted(marks,key=int)
#if you want to print only the highest
print "%s,%s"%(name,marks[-1])
I'm trying to learn python and I'm doing a problem out of a book but I'm stuck on one question. It asks me to read a file and each line contains an 'a' or a 's' and basically I have a total which is 500. If the line contains an 'a' it would add the amount next to it for example it would say "a 20" and it would add 20 to my total and for s it would subtract that amount. In the end I'm supposed to return the total after it made all the changes. So far I got
def NumFile(file:
infile = open(file,'r')
content = infile.readlines()
infile.close()
add = ('a','A')
subtract = ('s','S')
after that I'm completely lost at how to start this
You need to iterate over the lines of the file. Here is a skeleton implementation:
# ...
with open(filename) as f:
for line in f:
tok = line.split()
op = tok[0]
qty = int(tok[1])
# ...
# ...
This places every operation and quantity into op and qty respectively.
I leave it to you to fill in the blanks (# ...).
A variation might be
f = open('myfile.txt','r')
lines = f.readlines()
for i in lines:
i = i.strip() # removes new line characters
i = i.split() # splits a string by spaces and stores as a list
key = i[0] # an 'a' or an 's'
val = int( i[1] ) # an integer, which you can now add to some other variable
Try adding print statements to see whats going on. The cool thing about python is you can stack multiple commands in a single line. Here is an equivalent code
for i in open('myfile.txt','r').readlines():
i = i.strip().split()
key = i[0]
val = int (i[1])