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
Related
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.
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()]
I am writing a code that basically asks for user input of an 8 digit number, that is then read from a text file to see if it is valid and then asks the user for quantity. It works fine up until it needs to calculate the total of the product (multiplied by quantity entered)? It produces this error:
Traceback (most recent call last):
File "C:\Users\User\Desktop\A453 Task 2.py", line 25, in <module>
price=float(itemsplit[2]) #price is
ValueError: could not convert string to float: 'magent,'
Here is my actual code:
loop=1
while loop==1:
print ("The Hardware Store")
print ("a - Place an order by barcode")
print ("x - Exit")
task=input("Please make your selection")
if task.lower()=="a":
print("The Hardware Store")
myfile=open("hardware_store.txt", "r") #this opens the text file
product_information=myfile.readlines() #reads the file and stores it
as a variable named variable 'details'
myfile.close() #closes the file
while True:
digits=input("Please enter your GTIN-8 code\n")
if len(digits) !=8: #if the digits aren't equal to 8 digits, the
input not accepted
print("Please enter a valid GTIN-8 code\n")
else:
break #if the code is the correct length, the loop ends
for line in product_information:
if digits in line:
productline=line
myfile=open("receipt.txt", "w") #opens receipt file
myfile.writelines("\n" + "+")
quantity=input("How much of the product do you wish to purchase?\n")
itemsplit=line.split(' ') #seperates into different words
price=float(itemsplit[2]) #price is
total=(price)*(quantity) #this works out the price
myfile.writelines("Your total spent on this product is: " +str("£:,.2f)".format(total)+"\n"))
if task.lower()=="x":
print("Thank you for visiting the hardware store, come again!")
break
else:
print("Sorry, please enter a valid input")
And here is the text file (named "hardware_store.txt")
16923577,Hammer,3.00,
78451698,32 lrg nails,2,
17825269,32 med nails,2.00,
58246375,32 sml nails,2.00,
21963780,Drill Bits set,7.00,
75124816,Lrg Brush,2.00,
78469518,Sml Brush,1.00,
58423790,Dust Pan,1.00,
88562247,32 lrg screws,2.00,
98557639,32 med screws,2.00,
37592271,32 sml screws,2.00,
50966394,screwdriver set,7.00,
75533458,wall bracket,0.70,
12345678, neodymium magent, 9.99
10101010, screws 12x50mm Pack 50, 2.79
I don't understand what is happening, it works up until you enter the desired quantity. Thanks in advance
You file hardware_store.txt has values separated on each lines by comma, not whitespace. You should split the line by ',', not by ' '.
You could also look at the CSV module in python to read your file.
In itemsplit list you have:
itemsplit[0] = "12345678,"
itemsplit[1] = "neodymium"
itemsplit[2] = "magent,"
itemsplit[3] = "9.99"
itemsplit[2] hasn't got any number to cast float.
You must use try ... except ... to catch the exception when no number is in your list item.
I've corrected your code:
so say we have a hardware_store.txtfile that contains:
12345678 5
task = ""
while task.lower() != "x":
print ("The Hardware Store")
print ("a - Place an order by barcode")
print ("x - Exit")
task=input("Please make your selection ")
if task.lower()=="a":
print("The Hardware Store")
myfile=open("hardware_store.txt", "r") #this opens the text file
product_information=myfile.readlines() #reads the file and stores it as a variable named variable 'details'
myfile.close() #closes the file
while True:
digits=input("Please enter your GTIN-8 code\n")
if not len(digits) == 8: #if the digits aren't equal to 8 digits, the input not accepted
print("Please enter a valid GTIN-8 code\n")
else:
break #if the code is the correct length, the loop ends
for line in product_information:
if digits in line:
#productline=line
myfile=open("receipt.txt", "w") #opens receipt file
myfile.write("\n" + "+")
quantity=input("How much of the product do you wish to purchase?\n")
quantity = int(quantity)
price = line.split(" ")[1]
price=float(price) #price is
total=(price)*(quantity) #this works out the price
myfile.write("Your total spent on this product is: £:({:.2f}){}".format(total, '\n'))
myfile.close()
else:
print("Sorry, please enter a valid input")
else:
print("Thank you for visiting the hardware store, come again!")
Running the code:
The Hardware Store
a - Place an order by barcode
x - Exit
Please make your selection a
The Hardware Store
Please enter your GTIN-8 code
12345678
How much of the product do you wish to purchase?
5
The Hardware Store
a - Place an order by barcode
x - Exit
Please make your selection x
Thank you for visiting the hardware store, come again!
receipt.txt:
\n
+Your total spent on this product is: £:(25.00)
You won't see \n in your text editor if you open receipt.txt, I've included the '\n' just to make it clear that there's a new line at the beginning, you'll just see an empty space in your editor followed by +Your reset of the text...
I'm making a code that shows a product list in an ordered way, and the user can input a GTIN-8 code and select an amount they wish to 'purchase'. So when the user inputs a GTIN-8 code, FullLine should be the product description etc which is in the product list and show the amount. However, the amount is appearing on a new line which I don't want. I've tried putting the newline after the product list, before it and under it, but it won't stay on the same line.
Here is the code:
nl="\n"
Products=open("Productsfile.txt","w")
Products.write(nl+"23456945, Thorntons Chocolate Box, £10.00")
Products.write(nl+"12376988, Cadburys Easter Egg, £15.00")
Products.write(nl+"76543111, Galaxy Bar, £1.00")
Products.write(nl+"92674769, Cadury Oreo Bar, £1.00")
Products.write(nl+"43125999, Thorntons Continental Box, £12.00")
Products.close()
Products=open("Productsfile.txt","r")
print(Products.read())
Receipt=open("ReceiptFile.txt","w")
Receipt.write("Here are your purchases: \n")
Receipt.close()
print("Please enter the GTIN-8 Codes of the products you want and how many")
IfFinished=""
while IfFinished != "Yes":
ProductsWanted=input("Please enter the GTIN-8 Code of the product: ")
AmountOfProducts=input("How many do you want? ")
with open("Productsfile.txt") as f:
for line in f:
if ProductsWanted in line:
FullLine=(line +"Amount: " +AmountOfProducts)
print(FullLine)
Receipt=open("ReceiptFile.txt","a")
Receipt.write(str(FullLine))
Receipt.close()
So when running, I get, e.g.:
23456945, Thorntons Chocolate Box, £10.00
Amount: 2
However I want the Amount on the same line
Using rstrip method, Change the FullLine=(line +"Amount: " +AmountOfProducts)
to FullLine=(line.rstrip() +"Amount: " +AmountOfProducts)
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 :)