I need my output to look nice, and it looks very sloppy.
--------Current output---------
Below are the players and their scores
John Doe 120
Sally Smooth 115
----------End current output----------
My desired output follows
-------Desired output-----------------
Below are the players and their scores
John Doe 120
Sally Smooth 115
--------End desired output-------------
my current code follows;
def main():
# opens the "golf.txt" file created in the Golf Player Input python
# in read-only mode
infile = open('golf.txt', 'r')
print("Below are the players and their scores")
print()
# reads the player array from the file
name = infile.readline()
while name != '':
# reads the score array from the file
score = infile.readline()
# strip newline from field
name = name.rstrip('\n')
score = score.rstrip('\n')
# prints the names and scores
print(name + " " + score)
# read the name field of next record
name = infile.readline()
# closes the file
infile.close()
main()
Try using the tab character to format your spaces better.
print(name + "\t" + score)
This should give you something closer to your desired output. But you may need to use two if some names are long.
You can add the names and the scores to a list and then print it as a table as
import numpy as np
name_list = ['jane doe' ,'sally smooth']
score = np.array([[102,],[106,]]) #make a numpy array
row_format ="{:>15}" * (len(name_list))
for name, row in zip(name_list, score):
print(row_format.format(name, *row))
Note: This depends on str.format()
This code will output:
jane doe 102
sally smooth 106
Related
The following is the problem and i have written the code.Can someone have the answer code shortened?
Suppose the file studentdata.txt contains information on grades students earned on various
assignments. Each line has the last name of a student (which you can assume is one word) and
the numeric grade that student received. All grades are out of 100 points. Students can appear
multiple times in the file.
Here’s a sample file:
Arnold 90
Brown 84
Arnold 80
Cocher 77
Cocher 100
Write a function that reads the data from the file into a dictionary. Then continue prompting the
user for names of students. For each student, it should print the average of that student’s grades.
Stop prompting when the user enters the name of a student not in the dictionary.
A sample run for the given file:
Enter name: Arnold
The average for Arnold is: 85.0
Enter name: Brown
The average for Brown is: 84.0
Enter name: Cocher
The average for Cocher is: 88.5
Enter name: Doherty
Goodbye!
Here is my code :
import os
PATH="C:/Users/user/Desktop/studentdata.txt"
fd=open("C:/Users/user/Desktop/studentdata.txt","r")
d=fd.read()
p1=r"\b[A-za-z]+\b"
p2=r"\b[0-9]+\b"
l1=re.findall(p1,d)
fd=open("C:/Users/user/Desktop/studentdata.txt","r")
l2=re.findall(p2,d)
d={}
for key,val in list(zip(l1,l2)):
if key not in d:
d[str(key)]=int(val)
else:
d[str(key)]+=int(val)
for key in d:
d[key]=d[key]/l1.count(key)
while True:
key=input("Enter name:")
if key not in d:
print("Goodbye!")
break
print("the average for "+key+" is: "+str(d[key]))
PATH = "C:/Users/user/Desktop/"
FILE = "studentdata.txt"
with open(PATH + FILE, 'r') as fp:
lines = fp.readlines()
notes_with_students = {}
for line in lines:
student = line.split()[0]
note = line.split()[1]
if student not in notes_with_students:
notes_with_students.setdefault(student, [int(note), 1])
else:
notes_with_students[student][0] += int(note)
notes_with_students[student][1] += 1
while True:
student = input("Enter name: ")
if student not in notes_with_students:
print("Goodbye!")
break
print("The average for {} is: {}".format(student, notes_with_students[student][0]/notes_with_students[student][1]))
This can be useful.
I'm trying to format my text line by line read from a .txt file. Firstly I'm just trying to figure out how to print just one line, then attempt multiple lines after. I've managed to print the text of one line, but when I try to format it they way I want it to look, a new line is created after I attempt to print the last word of the line (using index of -1). The last word is creating a new line, so I think I need to find a way to read the lines as seperate strings but I'm not sure.
This is the code for my program:
def makeTuple (employee):
myTuple = employee.split(" ")
payroll, salary, job_title, *othernames, surname = myTuple
myTuple = tuple(myTuple)
return(myTuple)
def printTuple (data):
employee_str = "{}, {} {:>8} {} {:>5}"
print(employee_str.format(data[-1], " ".join(data[3:-1], data[0], data[2], data[1]))
get_file = input(str("Please enter a filename: "))
path = get_file + ".txt"
try:
text_file = open(path, "r")
except IOError:
print('The file could not be opened.')
exit()
record = text_file.readline()
myTuple = makeTuple(record)
printTuple(myTuple)
This is the text file I'm reading from:
12345 55000 Consultant Bart Simpson
12346 25000 Teacher Ned Flanders
12347 20000 Secretary Lisa Simpson
12348 20000 Wizard Hermione Grainger
The output I get at the moment is:
Simpson
, Bart 12345 Consultant 55000
Whereas I want it to look like:
Simpson, Bart 12345 Consultant 55000
You are getting a newline after "Simpson" because that's what's in the text file.
Use the function strip() (Documentation) to remove the newlines when you read the line.
Change the following one line of code and your program should work.
record = text_file.readline().strip()
You can do it with split and join:
s = '''Simpson
, Bart 12345 Consultant 55000'''
print(''.join(s.split('\n')))
Context: I have written a program that asks the user to enter the name and score (integer) for a user-defined quantity of players. The program then formats, slices and stores the values in a file named golf.dat
Issue: I am trying to expand my program to allow it to identify the player with the lowest score and print the name and score of the lowest scorer.
My code:
def playerDataInput(playerQuantity):
outputFile = open("golf.dat", "w")
for currentPlayer in range (1, playerQuantity + 1):
playerName = (input("Please enter player " + format(currentPlayer, "d",)+"'s name: "))
playerScore = (input("Please enter player " + format(currentPlayer, "d",)+"'s score: "))
outputFile.write(playerName + "\n")
outputFile.write(str(playerScore) + "\n")
outputFile.close()
def playerDataOutput():
inputFile = open("golf.dat", "r")
playerName = inputFile.readline()
while playerName != "":
playerScore = inputFile.readline()
playerName = playerName.rstrip("\n")
playerScore = playerScore.rstrip("\n")
print(playerName + ("'s score was:"), playerScore)
playerName = inputFile.readline()
inputFile.close()
def lowestScorer():
integers = open("golf.dat", "r")
lowestScore = 0
for score in integers:
if lowestScore >= int(score.strip()):
lowestScore = int(score.strip())
integers.close()
print("The lowest score was: ", lowestScore)
I've tried: I have tried (in vein) to write a function (lowestScorer) to extract and display the lowest value, but it didn't occur to me at first, but this is obviously going to fail, based on the way my data is stored.
Where you can help: suggest if there is any Pythonic way of adapting my code (rather than re-writing), to allow my program to identify and display the name and scorer of the lowest scorer / integer, saved in my golf.dat file?
My suspicion is that I should have written this program with two lists that hold names and scores respective and then written these to golf.dat (for easy extraction and analysis) or created these two lists (as sublists, thus holding names and integer score values separately) but gone a step further and saved them within a master list.
My goal is to have two programs. One will ask the user to input a test name and then a test score repeatedly until the user hits enter. This information will be stored in a .txt file. The second program will pull the information from the .txt file and print it into a format like something below with the test scores and a final average:
Reading six tests and scores
TEST SCORE
objects 88
loops 95
selections 86
variables 82
Average Test Score is
So far I have this for the first program to generate the txt document:
def main():
myfile = open('test.txt', 'w')
test = input('Please enter test name or enter to quit ')
while test != '':
score = int(input('Enter % score on this test '))
myfile.write(test + '\n')
myfile.write(str(score) + '\n')
test = input('Please enter test name or enter to quit ')
myfile.close()
print('File was created successfully')
main()
The second program looks like this and is in rough shape:
def main():
f = open('test.txt', 'r');
text = f.read();
f.close()
Main()
Any suggestions or examples? I’m really struggling.
First program / write
I recommend using \t between name and score instead of \n.
like this...
name1 100
name2 75
name3 10
...
It will help you when you read a file.
name, score = file.readline().split('\t')
Additionally, How about check input validation? whether input value in the valid range.
Second program / read
Using format is a nice way.
total, count = 0, 0
fmt = "{name:<16}\t{score:<5}"
header = fmt.format(name="TEST", score="SCORE")
print(header)
while ( ... ):
total += score
count += 1
... # read file
row = fmt.format(name=name, score=score)
print(row)
print("Average Test Score is ", total/count)
I am trying to access data stored in a text file and sorting the data by specific lines in the text file.
Here is the data, text in " " is not included in the text file but for reference:
741258 "This is a student ID"
CSF105 "This is a course module"
39 "This is a module mark"
CSF104
86
CSF102
71
CSF106
16
CSF103
3
CSF100
88
CSF101
50
123456
CSF100
50
CSF101
98
CSF102
74
CSF103
84
CSF104
65
CSF105
79
CSF106
100
I need to extract the Student ID then build a list of modules and marks based on that student ID and produce the average marks for that student, I am using Classes and methods to sort the data and if I input it directly via a function just using one set of data i.e.
id1 = Student("754412")
id1.addMark(Mark("CSF102", 90))
id1.addMark(Mark("CSF101", 80))
id1.addMark(Mark("CSF101", 42))
id1.addMark(Mark("CSF104", 90))
print(id1)
print("The Students average mark is: ", id1.calculateAverageMark())
It works. How do I get python to read the lines and determine which is the next student ID in the list as to not continuously read after the last mark/module for the student? I hope this makes sense.
Just loop over the open file object and use next() to get a next line in the loop to read both course and course mark.
If a line does not start with CSF then it is assumed that we started reading a new student:
with open(inputfilename) as infh:
student = Student(next(infh).strip())
# auto-strip all lines
infh = (l.strip() for l in infh)
for line in infh:
if line.startswith('CSF'):
student.addMark(Mark(line, next(infh)))
else:
# new student, output information on the previous student first
print(student)
print("The Students average mark is: ", student.calculateAverageMark())
student = Student(line)
# last student info
print(student)
print("The Students average mark is: ", student.calculateAverageMark())