Reading from and printing records from a file - python

I need to be able to read from a file and print records if a variable entered is pre-existent in the file. I have tried to open the file as 'f' however that would only read the first line in the file, heres my code:
problem = input("Please select from one of these: sink, faucet, toilet, shower, heater, other: \n")
temporaryFile = open("plumberInfo.txt" , "r")
for row in temporaryFile:
record = row.split(",")
if record[6] == problem:
Pforename = record[1]
Psurname = record[2]
Pfee = record[3]
Pexperience = record[4]
Prate = record[5]
print("You have selected", Pforename, Psurname, "they have", Pexperience , "years of experience and they specialise in", problem, "\n")
else:
print("Invalid input")
plumberSearch() #This part isn't relevant
Also below I have attached some contents of the file:
743,Auryn,Smith,42.00,6,44.50,faucet,extra
583,Michael,Lanlow,25.00,8,75.00,sink,extra
731,Hanna,Taylor,42.00,14,55.00,heater,extra
981,Tomie,Agen,32.00,6,44.50,toilet,extra
I don't understand the problem as it worked fine for when I was searching by the ID ([record0]). There is no traceback error, it just states invalid input which means record[6] != problem, however it is equal.

When I try the code on my machine, printing record shows me that the last item contains a new line character at the end. Thus when you search for sink, you're essentially doing the search sink == sink\n, hence why you get invalid input.
Reading in the file also reads in the new line, and you need to be aware. You would need to remove it before doing the comparison.

Related

How to fix my leaderboard for my Music Quiz

I'm making a Music Quiz for a school project.
I've made a working game however I cannot get the leaderboard (which should be text and is saved as leaderboard.txt) to show different names as it overwrites the previous name.
For example, if "Sam" was to get a score of 9 and "Ben" was to get a score of 3, it would show up as "Ben-3-9" which is not what I'm after.
I am trying to get my leaderboard to work like:
Sam - 9
Ben - 3
...
My code looks like this right now:
username = input("What is your username?")
# this will ask for the persons name
password = str(input("What is the password?"))
# this will ask for a password which has been set already
if password == "1234":
print("User Authenticated")
# if the password is incorrect, tell the user so and exit
elif password != "1234":
print("Password Denied")
exit()
# GAME
# Creating a score variable
score=0
x = 0
# Reading song names and artist from the file
read = open("songnames.txt", "r")
songs = read.readlines()
songlist = []
# Removing the 'new line' code
for i in range(len(songs)):
songlist.append(songs[i].strip('\n'))
while x == 0:
# Randomly choosing a song and artist from the list
import random
choice = random.choice(songlist)
artist, song = choice.split('-')
# Splitting the song into the first letters of each word
songs = song.split()
letters = [word[0] for word in songs]
# Loop for guessing the answer
for x in range(0, 2):
print(artist, "".join(letters))
guess = str(input("Guess the song!"))
if guess == song:
if x == 0:
score = score + 3
break
if x == 1:
score = score + 1
break
quit()
# Printing score, Then waiting to start loop again.
import time
print("Your score is", score)
print("Nice Work!")
time.sleep(3)
leaderboard = open("leaderboard.txt", "r+")
leaderboard.write(username + '-' + '{}'.format(score))
leaderboard.close()
leaderboard = open("leaderboard.txt", "r+")
leaderboardlist = leaderboard.readlines()
print(leaderboardlist)
leaderboard.close()
PS: this is not 100% my code I am trying to get help from different places as my school has not taught us how to code yet due to the pandemic closing down schools.
When you do this:
leaderboard = open("leaderboard.txt", "r+")
leaderboard.write(username + '-' + '{}'.format(score))
you open the leaderboard in read-and-write mode, but it will start writing at the beginning of the file, overwriting whatever is there. If you just want to add new scores to the leaderboard, the simplest would be to open the file in "append" mode "a":
with open("leaderboard.txt", "a") as leaderboard:
leaderboard.write(username + '-' + '{}'.format(score))
Alternatively, you could open the file in "r" mode, then first read all the lines (scores) in a list or dictionary, merge / update them with the current player's new score (e.g. adding to the last score, replacing the last score, or getting the max of the new and last score of that player), and then open the file again in "w" mode and write the updated scores. (Left as an exercise to the reader.)
The problem lies within the final few lines of code, where you are writing to the leaderboard.txt file.
Using "r+" indicates that you are updating (reading and writing) the file. Opening a file this way, moves the cursor at the beginning of the file. Therefore any attempt to write to the file will override whatever is already there.
The proper way to do it, is to open the file using "a" (or "a+" if you are planning to read as well). This is append mode and will move the cursor to the end of the file.
Some other general notes:
Use the with-as statement to handle closing the file automatically after you are done.
Use f-strings as opposed to string concatenation to increase readability
With that in mind, here's the code:
with open("leaderboards.txt", "a") as f:
f.write(f"{username}-{score}")
For more on files, check this question.
For more on f-strings, check this quite extensive overview of them.

Passwords/username from a file

I've recently been having trouble writing a program that involves taking the password and username from a .txt file. So far I have written:
username_file = open("usernameTest1.txt","rt")
name = username_file.readlines()
username_file.close()
print(username_file)
print(name)
print(name[0])
print()
print(name[1])
Player1Name = name[0]
print(Player1Name)
nametry = ""
while nametry != (name[0]):
while True:
try:
nametry = input("What is your Username player1?: ")
break
except ValueError:
print("Not a valid input")
(The various prints are to help me to see what the error is)
The password is successfully extracted from the file however when it is put into a variable and put through an if statement, it doesn't work!
Any help would be much appreciated!
Hopefully this is a simple fix!
Your problem is that readlines() function lets the \n character remain in your text lines and that causes the texts to not match. You can use this instead when opening the file:
name = username_file.read().splitlines()
give it a try.
the readlines function doen't strip the newline character from the end of the lines, so eventough you wrote "samplename" as input, it won't equal "samplename\n".
You can try this:
name = [x.rstrip() for x in username_file.readlines()]

How do I put each record inputted by a user within a loop in a text file

So, I have my code which is for a user wanting to loan books from a library or somewhere. They input the code for the book that they'd like to loan, I have the code with the assigned name, price etc in a text file. They input the quantity of the book that they'd like to loan then a price is calculated. If they want to loan more books, the code loops back and they can repeat the process. I want to make a separate receipt file, which stores everything that the user enters within the loop in this receipt file, and then adds everything together. I read some stuff and tried this, but there is an error and I don't know what I did wrong. Here is my code:
task=input("Enter 'b' to borrow a book, press 'x' to exit. \n")
if task.lower()== "b":
myfile=open("books.txt", "r+")
details=myfile.readlines()
while True:
book=input("Enter the 8 digit book code. \n")
while len(book) !=8
print("Your code is not 8 digits long, please try again.\n")
f = open("books.txt", "r+")
for line in f.readlines():
quantity=input("How many copies of the book do you wish to purchase?\n")
t = line.split(" ")
price = float(t[3])
code = t[1]
NameOfBook = t[2]
total=(price)* int(quantity)
with open("receipt.txt", "w") as receiptFile:
receiptFile.write(str(code))
receiptFile.write(float(NameOfItem))
receiptFile.write(int(quantity))
receiptFile.write(str(price))
receiptFile.write(str(total))
break
answer = input("Do you want to loan another book? Enter 'yes' if you would like to. ")
if answer == "yes":
continue
else:
break
What I tried to enter is this:
with open("receipt.txt", "w") as receiptFile:
receiptFile.write(str(code))
receiptFile.write(float(NameOfBook))
receiptFile.write(int(quantity))
receiptFile.write(str(price))
receiptFile.write(str(total))
I assumed that it would open the file that I made named receipt.txt and then write in each thing the user inputs, however I ended with no success. This came up instead:
Traceback (most recent call last):
File "F:\PYTHOn\New python edited for loop.py", line 19, in <module>
receiptFile.write(float(NameOfBook))
ValueError: could not convert string to float: 'Narnia,'
Please help if possible. thanks :)

Reading the next line of a file

im new to this site and I know alot of people aren't very happy when somebody asks a question previously asked. However, I wish to ask despite it being previously asked beacause all the answers I found did not make much sense to me (im new to python!), so I was wondering if somebody could dumb it down for me or directly correct my code.
Im writing a code where the user inputs a GTIN-8 code and it searches a csv excel file for that code, it then reads the appropriate information about the product (price,ect...) and prints it out. However I cant search the second line of the file for some reason. Here is my code:
#csv is imported to read/write to the file
import csv
#Each Product is printed alongside it's GTIN-8 code and Price
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("~ Welcome to Toms bits and bobs ~")
print("Pencil, 12346554, £0.40")
print("50 Staples, 12346882, £1.00")
print("50 Paper Clips, 12346875, £1.20")
print("Large Eraser, 12346844, £1.50")
print("100 A4 Sheets, 12346868, £2.00")
print("100 A3 Sheets, 12346837, £2.50")
print("25 Byro Pens, 12346820, £2.20")
print("Handwriting Pen, 12346899, £5.50")
print("50 Split Pins, 12346813, £0.60")
print("Office Chair, 12346912, £25.00")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
#The file is opened and the user inputs the code for the product they
#wish to find.
file = open("Product_list.csv", "r")
purchase = input(print("Please enter the GTIN-8 code of the product you wish to purchase e.g 12346554"))
line = file.readline()
data = line.split(",")
if data[0] == purchase:
while(line):
print ("Product: ", data[1])
print ("GTIN-8 code: ", data[0])
print ("Stock: ", data[2])
print ("Description: ", data[3])
print ("Price: ", data[4])
line = file.readline()
break
else:
print("Product not found")
file.close()`
You are reading second line but because of the break, you never get a chance to use it since your code always breaks out of while loop if it enters there. Just remove it and your code should work fine.
Also, assuming your syntax is correct on this line.
purchase = input(print("Please enter the GTIN-8 code of the product you wish to purchase e.g 12346554"))
^^^^^This will cause a syntax error. You should remove this print as well

How can i write this function that mostly prints to a file?

So I posted about another part of this code yesterday but I've run into another problem. I made a character generator for an RPG and im trying to get the program the output of a character sheet function to a .txt file, but i think whats happening is that the function may return a Nonevalue for some of the stats (which is totally normal,) and then i get an error because of that when i try to write to a .txt file. I'm totally stumped, and help would be vastly appreciated!
# Character Sheet Function.
def char_shee():
print "Name:", name
print "Class:", character_class
print "Class Powers:", class_power
print "Alignment:", alignment
print "Power:", pow, pow_mod()
print "Intelligence:", iq, iq_mod()
print "Agility:", agi, agi_mod()
print "Constitution:", con, con_mod()
print "Cynicism:", cyn, cyn_mod()
print "Charisma:", cha, cha_mod()
print "All Characters Start With 3 Hit Dice"
print"""
\t\t{0}'s History
\t\t------------------
\t\tAge:{1}
\t\t{2}
\t\t{3}
\t\t{4}
\t\t{5}
\t\t{6}
\t\t{7}
\t\t{8}
\t\t{9}
\t\tGeneral Disposition: {10}
\t\tMost important thing is: {11}
\t\tWho is to blame for worlds problems: {12}
\t\tHow to solve the worlds problems: {13}
""".format(name, age, gender_id, ethnic_pr, fcd, wg, fogo_fuck, cur_fam,fam_fuk, nat_nur, gen_dis, wha_wor, who_pro, how_pro)
char_shee()
print "Press enter to continue"
raw_input()
# Export to text file?
print """Just because I like you, let me know if you want this character
saved to a text file. Please remember if you save your character not to
name it after something important, or you might lose it.
"""
text_file = raw_input("Please type 'y' or 'n', if you want a .txt file")
if text_file == "y":
filename = raw_input("\nWhat are we calling your file, include .txt")
target = open(filename, 'w')
target.write(char_shee()
target.close
print "\nOk I created your file."
print """
Thanks so much for using the Cyberpanky N.O.W Character Generator
By Ray Weiss
Goodbye
"""
else:
print """
Thanks so much for using the Cyberpanky N.O.W Character Generator
By Ray Weiss
Goodbye
"""
EDIT: Here is the output i get:
> Please type 'y' or 'n', if you want a .txt filey
>
> What are we calling your file, include .txt123.txt <function char_shee
> at 0x2ba470> Traceback (most recent call last): File "cncg.py", line
> 595, in <module>
> target.write(pprint(char_shee)) TypeError: must be string or read-only character buffer, not None
Using print writes to sys.stdout, it doesn't return a value.
You you want char_shee to return the character sheet string to write it to a file, you'll need to just build that string instead.
To ease building the string, use a list to collect your strings:
def char_shee():
sheet = []
sheet.append("Name: " + name)
sheet.append("Class: " + character_class)
# ... more appends ...
# Return the string with newlines
return '\n'.join(sheet)
you forgot parenthesis here:
target.write(char_shee())
target.close()
and as #Martijn Pieters pointed out you should return value from char_shee(), instead of printing them.

Categories