Python rewriting data text file grades program - python

Searching for help with a program. The task is to rewrite the program from this question.
The directions are to create a function called def username(first, last):. The function username will have two parameters, first and last. The output will be the same as the original text file grade program.
This is what I have so far:
def username(first, last):
for lines in aList:
n = lines.split()
first = n[0][0].lower()
last = n[1][0:4].lower()
resultName = first + last + "001"
return resultName
def main():
inFile = open("grades.txt", "r")
aList = inFile.readlines()
print(username)
inFile.close
main()
the output I'm receiving:
function username at 0x7f68f83a5158
the output I should be receiving:
>>>username('Jane', 'Smith')
jsmit001
Any insight on what I can do to make this program run correctly would be appreciated.
I played around with this program and found that:
def username(first, last):
inFile = open("grades.txt", "r")
aList = inFile.readlines()
for lines in aList:
n = lines.split()
first = n[0][0].lower()
last = n[1][0:4].lower()
resultName = first + last + "001"
return resultName
infile.close
def main():
print(username(first = "Jane", last = "Smith"))
main()
it works now, but gives me only the first line from my text file. The output is correct, but I need all 5 usernames. I believe it is an indentation problem somewhere but I am unsure where it is. By un-indenting "return resultName" once my output was the last line in my text file.

print(username)
Here you miss the arguments (first,last). At the moment you just ask where the function is saved, so where the pointer is set to

An issue with your program.
You have not called the username function. So when you do
print(username)
the output that you get is the address where the function is stored.
Hope it helps.
def username(first, last):
for lines in aList:
n = lines.split()
first = n[0][0].lower()
last = n[1][0:4].lower()
resultName = first + last + "001"
return resultName
def main():
inFile = open("grades.txt", "r")
aList = inFile.readlines()
#first == aList[0]
#last = aList[1] #Something like this I expect
print(username) ##Pass the values to the function which will return you the value "resultName" which you want to print
inFile.close()
main()

Related

Why does points not change to the users score and instead remains as the temporary value of 0?

points = "temp"
a = "temp"
f = "temp"
def pointincrementer():
global points
points = 0
for line in f:
for word in a:
if word in line:
scorelen = int(len(user+","))
scoreval = line[0:scorelen]
isolatedscore = line.replace(scoreval,'')
if "," in line:
scorestr = isolatedscore.replace(",","")
score = int(scorestr)
points = score + 1
print(points)
def score2():
f = open('test.txt','r')
a = [user]
lst = []
for line in f:
for word in a:
if word in line:
pointincrementer()
print(points)
point = str(points)
winning = (user+","+point+","+"\n")
line = line.replace(line,winning)
lst.append(line)
f.close()
f = open('test.txt','w')
for line in lst:
f.write(line)
f.close()
print("Points updated")
user = input("Enter username: ") #change so user = winners userid
with open('test.txt') as myfile:
if user in myfile.read():
score2()
else:
f = open('test.txt','r')
f2 = f.read()
f3 = (f2+"\n"+user)
f.close()
f = open('test.txt','w')
f.write(f3)
f.close()
score2()
This is paired with test.txt, which looks like this:
one,1,
two,5,
three,4,
four,94,
When this code is run, it it will ask the user their name (as expected) and then will print 0 (when it should instead print the user's score) and then Points updated. Anybody know how to sort this out?
There are many problems with your code. You should not be using global variables like that. Each function should be passed what it needs, do its computing, and return values for the caller to handle. You should not be reading the file multiple times. And you can't write the file while you still have it open with the with statement.
Here, I read the file at the beginning into a Python dictionary. The code just updates the dictionary, then writes it back out at the end. This makes for a simpler and more maintainable structure.
def readdata(fn):
data = {}
for row in open(fn):
info = row.strip().split(',')
data[info[0]] = int(info[1])
return data
def writedata(fn,data):
f = open(fn,'w')
for k,v in data.items():
print( f"{k},{v}", file=f )
def pointincrementer(data,user):
return data[user] + 1
def score2(data, user):
points = pointincrementer(data, user)
print(points)
data[user] = points
print("Points updated")
user = input("Enter username: ")
data = readdata( 'test.txt' )
if user not in data:
data[user] = 0
score2(data, user)
writedata( 'test.txt', data )
The f in pointincrementer() refers to the "temp" string declared on the third line. The f in score2() refers to the file handle declared immediately below the function header. To get around this, you can pass the file handle into pointincrementer():
def pointincrementer(file_handle):
global points
points = 0
for line in file_handle:
for word in a:
if word in line:
scorelen = int(len(user+","))
scoreval = line[0:scorelen]
isolatedscore = line.replace(scoreval,'')
if "," in line:
scorestr = isolatedscore.replace(",","")
score = int(scorestr)
points = score + 1
print(points)
def score2():
file_handle = open('test.txt','r')
a = [user]
lst = []
for line in f:
print(line)
for word in a:
if word in line:
pointincrementer(file_handle)
print(points)
point = str(points)
winning = (user+","+point+","+"\n")
line = line.replace(line,winning)
lst.append(line)
f.close()
f = open('test.txt','w')
for line in lst:
f.write(line)
f.close()
print("Points updated")
This leads to a parsing error. However, as you haven't described what each function is supposed to do, this is the limit to which I can help. (The code is also extremely difficult to read -- the lack of readability in this code snippet is likely what caused this issue.)

Trouble with matching variables to line in txt, and removing line

I am having trouble with matching variables to lines in txt, and removing the lines.
I am currently doing a hotel room booking program in which I am having trouble removing a booking from my text file.
This is how my lines in my text file are formatted:
first_name1, phonenumber1 and email 1 are linked to entry boxes
jeff;jeff#gmail.com;123123123;2019-06-09;2019-06-10;Single Room
def edit_details(self,controller):
f = open("Bookings.txt")
lines = f.readlines()
f.close()
x = -1
for i in lines:
x += 1
data = lines[x]
first_name1 = str(controller.editName.get())
phonenumber1 = str(controller.editPhone.get())
email1 = str(controller.editEmail.get())
checkfirst_name, checkemail, checkphone_num, checkclock_in_date, checkclock_out_date, checkroom = map(str, data.split(";"))
if checkfirst_name.upper() == first_name1.upper() and checkemail.upper() == email1.upper() and checkphone_num == phonenumber1:
controller.roomName.set(checkfirst_name)
controller.roomEmail.set(checkemail)
controller.roomPhone.set(checkphone_num)
controller.roomCheckin.set(checkclock_in_date)
controller.roomCheckout.set(checkclock_out_date)
controller.roomSelect.set(checkroom)
print(controller.roomName.get())
print(controller.roomSelect.get())
controller.show_frame("cancelBooking")
break
elif x > len(lines) - int(2):
messagebox.showerror("Error", "Please Enter Valid Details")
break
I have the user to enter their details to give me the variables but I don't know how to match these variables to the line in the text file to remove the booking.
Do I have to format these variables to match the line?
This is what i have tried but it deletes the last line in my file
line_to_match = ';'.join([controller.roomName.get(),controller.roomEmail.get(),controller.roomPhone.get()])
print(line_to_match)
with open("Bookings.txt", "r+") as f:
line = f.readlines()
f.seek(0)
for i in line:
if i.startswith(line_to_match):
f.write(i)
f.truncate()
I have kind of added a pseudocode here. You can join the variables using ; and validate if the line startswith those details, like below.
first_name1, phonenumber1, email1 = 'jeff', 'jeff#gmail.com', '123123123'
line_to_match = ';'.join([first_name1, email1, phonenumber1])
for i in line:
...
if i.startswith(line_to_match):
# Add your removal code here
...

List program not working

I have written a python program to act as a shopping list or some other list editor. It displays the list as it is, then asks if you want to add something, then asks is you want to see the newest version of the list. Here is the code:
#!/usr/bin/python
import sys
def read():
f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
myList.append(line)
print(myList)
myList = []
f.close()
def add_to(str):
newstr = str + "\n"
f = open("test.txt","a") #opens file with name of "test.txt"
f.write(newstr)
f.close()
read()
yes = "yes"
answerone = raw_input("Would you like to add something to the shopping list?")
if answerone == yes:
answertwo = raw_input("Please enter an item to go on the list:")
add_to(bob)
answerthree = raw_input("Would you like to see your modified list?")
if answerthree == yes:
read()
else:
sys.exit()
else:
sys.exit()
When it displays the list it displays it in columns of increasing length.
Instead of this, which is how it appears in the text file:
Shopping List
Soap
Washing Up Liquid
It displays it like this:
['Shopping List\n']
['Shopping List\n', 'Soap\n']
['Shopping List\n', 'Soap\n', 'Washing Up Liquid\n']
I was wondering whether anyone could help me understand why it does this, and how to fix it.
FYI I am using python 2.6.1
EDIT: Thanks to all who commented and answered. I am now trying to edit the code to make it sort the list into alphabetical order, but it is not working. I have written a piece of test code to try and make it work (this would be in the read() function):
#!usr/bin/python
f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
myList.append(line)
f.close()
print myList
subList = []
for i in range(1, len(myList)):
print myList[i]
subList.append(myList[i])
subList.sort()
print subList
This is the text file:
Test List
ball
apple
cat
digger
elephant
and this is the output:
Enigmatist:PYTHON lbligh$ python test.py
['Test List\n', 'ball\n', 'apple\n', 'cat\n', 'digger\n', 'elephant']
ball
apple
cat
digger
elephant
['apple\n', 'ball\n', 'cat\n', 'digger\n', 'elephant']
Once again, any troubleshooting would be helpful.
Thanks
P.S I am now using python 2.7.9
In read, you are printing the whole list after each line read. You just need to print the current line:
def read():
f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
myList.append(line)
print(line)
myList = [] # also you are setting it to empty here
f.close()
Also, you should be using with statement to ensure the closure of the file; and there is no reason to use myList since you are not returning any changes yet; and you'd want to strip() extra whitespace from the beginning and end of the items, so the minimum would be:
def read():
with open('test.txt') as f:
for line in f:
line = line.strip()
print line # this is python 2 print statement
If you need to return a value:
def read():
my_list = []
with open('test.txt') as f:
for line in f:
line = line.strip()
my_list.append(line)
print line
return my_list

Read and write to a list of names and scores - python

I am trying to create a program that gives the user a short quiz and create a score, which I have done, then I would like to add them to a list in a .txt file. In the program I will ask them their name, so say I have a list such as this;
Bob,7
Bill,5
Jane,6
and someone takes the quiz and inputs the name Bob and gets a score 4 the list will update to;
Bob,4
Bill,5
Jane,6
or someone new takes a quiz, Sarah it will change to;
Bob,4
Bill,5
Jane,6
Sarah,7
So far I have;
import random
file = open("scores.txt", "r")
UserScore=random.randint(0,10)
lines = file.readlines()
file.close()
student=input('What is your name? ')
file = open("scores.txt", "w")
for line in lines:
line = line.strip()
name, score = line.strip().split(",")
if name!=student:
file.write(line)
else:
file.write(name +',' +str(UserScore))
I've randomised the score for now to make it easier to read, however that will be from what the user answered correctly, and I thought this code would read the file then check each name from each line and if the name they entered is the same to the name in the list the line will be replaced with the name and score. However, the file just ends up blank, what am I doing wrong?
Here is what I think is a better idea using the Python pickle module:
In [1]: import pickle
In [2]: scores={'Bob':75, 'Angie':60, 'Anita':80} #create a dict called scores
In [3]: pickle.dump(scores,open('scores.dat','wb')) #dump the pickled object into the file
In [4]: !ls scores.dat #verify that the file has been created
scores.dat
In [5]: !cat scores.dat #list out the file
(dp0
S'Bob'
p1
I75
sS'Angie'
p2
I60
sS'Anita'
p3
I80
s.
In [9]: tscores = pickle.load(open('scores.dat','rb')) #Verification: load the pickled object from the file into a new dict
In [10]: tscores #Verification: list out the new dict
Out[10]: {'Angie': 60, 'Anita': 80, 'Bob': 75}
In [11]: scores == tscores #Verify that the dict object is equivalent to the newly created dict object
Out[11]: True
I tried your code and the first time you run it, then you rewrite the file in one single line. So the next time you run the script on this single line file, you get an unpack exception in the split function and hence you write nothing to the file, resulting in an empty file.
A solution could be to add the newline char again when writing the lines to the file.
import random
file = open("scores.txt", "r")
UserScore=random.randint(0,10)
lines = file.readlines()
file.close()
student=input('What is your name? ')
file = open("scores.txt", "w")
for line in lines:
line = line.strip()
name, score = line.strip().split(",")
if name!=student:
file.write(line + '\n')
else:
file.write(name +',' +str(UserScore) + '\n')
This should do what you want
import random
file = open("scores.txt", "r")
UserScore=random.randint(0,10)
lines = file.readlines()
file.close()
student=input('What is your name? ')
flag = True
file = open("scores.txt", "w")
for line in lines:
line = line.strip()
name, score = line.strip().split(",")
if name!=student:
file.write(line + '\n')
else:
file.write(name +',' +str(UserScore) + '\n')
flag = False
if flag:
file.write(student +',' +str(UserScore) + '\n')
I adjusted a bit of your code and took the liberty to remove the random part and name, score part. But I got some working code. I assume you can make it work for your situation.
file = open("scores.txt", "r+")
lines = file.readlines()
file.close()
us = 15
student = input('What is your name? ')
ls = []
file = open("scores.txt", "r+")
found_student = False
for line in lines:
line = line.strip()
ls = line.split(",")
print("Parsing: " + str(ls))
if not line:
print("Empty line")
pass
elif ls[0] != student:
file.write(line + "\n")
else:
found_student = True
file.write(ls[0] + ',' + str(us) + "\n")
if not found_student:
file.write(student + ',' + str(us) + "\n" )
file.close()

Python: Reading individual elements of a file

I am attempting to read in individual elements of a file. In this example, the first element of each line is to be the key of a dictionary. The next five elements will be a corresponding value for said key in list form.
max_points = [25, 25, 50, 25, 100]
assignments = ['hw ch 1', 'hw ch 2', 'quiz ', 'hw ch 3', 'test']
students = {'#Max': max_points}
def load_records(students, filename):
#loads student records from a file
in_file = open(filename, "r")
#run until break
while True:
#read line for each iteration
in_line = in_file.readline()
#ends while True
if not in_line: break
#deletes line read in
in_line = in_line[:-1]
#initialize grades list
grades = [0]*len(students['#Max'])
#set name and grades
name, grades[0], grades[1], grades[2], grades[3], grades[4] = in_line.split()
#add names and grades to dictionary
students[name] = grades
print name, students[name]
filename = 'C:\Python27\Python_prgms\Grades_list.txt'
print load_records(students, filename)
The method I have now is extremely caveman, and I would like to know what the more elegant, looping method would be. I have been looking for a while, but I can't seem to find the correct method of iteration. Help a brotha out.
Another way of doing it:
def load_records(students, filename):
with open(filename) as f:
for line in f:
line = line.split()
name = line[0]
students[name] = map(int, line[1:])
print name, students[name]
It seems a bit strange that the student dictionary contains both the scores and a parameter #Max though - a key has two meanings, is it a student's name or parameter's name? Might be better to separate them.
I had an assignment similar to this last year.
def load_records(students, filename):
file = open(filename, 'r')
s = ""
while s != None: # loop until end of file is reached
s = file.readline()
# manipulate s how you need
Also, you should use inline comments like above, it makes the code much easier to read compared to how you have it now.

Categories

Resources