Python - Keeping text file in one line? - python

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)

Related

Could not convert string to float?

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...

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 :)

Sending information gathered from questionnaire to a Python document?

I'm brand new to both Python and StackOverflow, and I have a problem that has been stumping me for the past couple of hours.
I am making a peer-evaluation script for my high-school class. When you run the script, you input your classmate's name, then you rate them 1-10 on effort, accountability, and participation. These 3 values are then averaged. This average is assigned to the variable "grade". Since each classmate is going to get multiple grades, I need to have the "grade" variable export to another Python document where I can average every grade for each respective classmate.
So far, I have the script create a .txt file with the same name as the evaluated classmate, and the grade integer is stored there. Does anyone know of a way that I can export that integer to a Python file where I can append each successive grade so they can then be averaged?
Thanks
Python peer evaluation script
def script():
classmate = input('Please enter your classmate\'s name: ')
classmateString = str(classmate)
effortString = input('Please enter an integer from 1-10 signifying your classmate\'s overall effort during LLS: ')
effort = int(effortString)
accountabilityString = input('Please enter an integer from 1-10 signifying how accountable your classmate was during LLS: ')
accountability = int(accountabilityString)
participationString = input('Please enter an integer from 1-10 signifying your classmate\'s overall participation: ')
participation = int(participationString)
add = effort + accountability + participation
grade = add / 3
gradeString = str(grade)
print ('Your grade for ', classmate, 'is: ', grade)
print ('Thank you for your participation. Your input will help represent your classmate\'s grade for the LLS event.')
filename = (classmateString)+'.txt'
file = open(filename, 'a+')
file.write(gradeString)
file.close()
print ('Move on to next classmate?')
yes = set(['yes','y','Yes','Y'])
no = set(['no','n','No','n'])
choice = input().lower()
if choice in yes:
script()
elif choice in no:
sys.exit(0)
else:
sys.stdout.write("Please respond with 'yes' or 'no'")
script()
script()
put
import name_of_script_file
at the top of your Python file, assuming they are in the same folder.
Then you can access the variable like:
name_of_script_file.variable_name

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

Can anyone help me debug my program

I'm in a beginning programming class and our program is to create a program to gather information on four different zip codes and five different types of coffee drinks to see if our friend should open up a coffee shop in that area.
My program will not accept my variables
My other problem with my program is it won't loop back around to get more input. I tried to reset the user answer to allow it to go back to the beginning but it doesn't read it.
I set up an accumulater for my if statement
Example
while UserAnswer == "yes":
ZipCode = input("Enter Zip Code: ")
print("Here are your menu choices: \n m = Cafe Mocha\n l = Cafe Latte ")
print(" r = Cafe Regular \n d = Cafe Regular Decafe \n c = Cafe Carmel")
CoffeeType = input("Enter your order: ")
Quantity = input("Enter quantity: ")
#Start inner loop with if statements to determine the quantity of the coffee
while UserAnswer == "no"
if ZipCode == 48026:
if CoffeeType == "m":
CM48026 = Quanity + CM48026'
My accumulater CM48026 doesn't save and at the end it prints out 0.
You need to provide an initial value for the accumulator. And that should be done outside the inner loop. Because you are using the same variable in the expression which provides the value for the accumulator.
So, doing a = b + a will not really work, as the value of a at the right is not really defined.
Moreover, there's a typo for the variable quantity, and that might actually be the reason why your code is not working!

Categories