Change the value of a text file Python - python

I am doing a POS machine which save the data in a text file. After customer buy item, the total quantity of the item in the text file will minus the quantity of the customer brought, but after I trying the code can works but the stock quantity in the text file remain unchanged. So, I found some answer from this SO question Reducing quantity in text file
, it works for them but mine can't. What gone I to do for my code work.
This is the contein of my text file named razershop.txt(id, name, price, quantity):
1 , Razer Deathadder V2, 349.00 , 100
2 , Razer Viper Ultimate, 419.00 , 105
3 , Razer Basilink Ulti, 599.00 , 35
4 , Razer Viper Mini, 139.00 , 295
5 , Raazer Deathadder X, 76.90 , 592
I used all_products to open my file:
all_products = [line.strip().split(',') for line in open('razershop.txt','r').readlines()]
This is the decrement item function code:
def decrement_item(item_id, quantity):
with open('razershop.txt', 'r') as fin:
# indexes for id and quantity
index_id = 0
index_quantity = 3
# output buffer
output = []
# Add headaer to output buffer
header = fin.readline().rstrip()
output.append(header) # header without '\n' at end of line
bfound_item = False
for line in fin:
# Check each line for item_id then upadte quantity
line = line.rstrip()
if not bfound_item:
# Only process if item_id has not been found yet
# Break line into separate fields
row = line.split()
current_id = row[index_id]
if current_id == item_id:
# Found item
# Check if sufficiente quantity
current_quantity = int(row[index_quantity])
if current_quantity >= quantity:
# Decrement quantity
current_quantity -= quantity
row[index_quantity] = str(current_quantity)
line = ' '.join(row)
bfound_item = True
else:
# Insufficient quantity for update
s = f"Sorry, available quantity is only {int(row[index_quantity])}"
raise Exception(s)
# Add line to output
output.append(line) # add copy since row changes with loop
# Update inventory file
with open('razershop.txt', 'w') as fout:
for line in output:
fout.write(line + '\n')
This is my Pos machine code which generate bill and will decrease the stock after customer buy it:
while(True):
banner()
choice = int(input("Please enter your option: "))
if choice == 1:
display_all()
elif choice == 2:
display_all()
print("Press 0 for payment")
item_lst = []
price_lst = []
quantity_lst = []
total_price = 0
prod_id = 999
while prod_id != 0:
prod_id = int(input("Enter the Product ID: "))
for item in all_products:
if int(item[0]) == prod_id:
quantity = int(input("Please enter the quantity: "))
item_lst.append(item[1])
quantity_lst.append(quantity)
price_q = float(item[2]) * quantity
price_lst.append(price_q)
total_price = total_price + price_q
decrement_item(prod_id , quantity)
order_summary(item_lst , price_lst , total_price , quantity_lst)
print(" ")
conf = input("Please confirm your order(Y/N): ")
if conf == "Y":
member = input("Do you have membership(Y/N): ")
if member == "Y":
total_price = total_price * 0.9
payment = float(input("Amount received: "))
change = payment - total_price
generate_bill(item, total_price, item_lst , price_lst , quantity_lst ,change , payment)
print(" ")
print("Thanks For shopping with Us :)")
sys.exit(0)
else:
payment = float(input("Amount received: "))
change = payment - total_price
generate_bill(item, total_price, item_lst , price_lst , quantity_lst ,change , payment)
print(" ")
print("Thanks For shopping with Us :)")
sys.exit(0)
else:
print("Continue Exploring the shop")
Output:
Upper output for customer to enter the item they want
Below part of the output which generate bill
(Sorry guys the output I can't put it in image form becuase SO not allow me so they changed my image to a link)
I had tried delete the with open('razershop.txt', 'r') as fin: and header = fin.readline().rstrip() and ( row = line.split() and change all the row variable to line fromfor line in fin: # Check each line for item_id then upadte quantity line = line.rstrip()from the decrement_item function. It end up with a infinity loop and last time I forgot what I had done with the code from the decrement_ item function the whole text in the txt file gone. I just want to know what should I do to make this work?

Related

I'm getting a ValueError: cannot convert string to float: ".". What is going on?

I am trying to write a function that takes in a file with numerical values, total them all up while excluding all numbers with a letter, and find the average. However, when I try to convert a number like "3.9" to float form, I get the ValueError: cannot convert string to float: ".". I know that if I just did a straight conversion of "3.9" to float form via float("3.9") type casting it would work.
def averageSpeed():
count = 0
total = 0
stripLst = 'abcdefghijklmnopqrstuvwxyz$'
while count < 2:
try:
filename = input("Enter a file to process: ")
instance = open(filename, "r")
content = instance.readlines()
for line in content:
lineSplit = line.split()
for element in lineSplit:
for letter in element:
for character in stripLst:
if letter == character:
lineSplit.remove(element)
for line in content:
for element in line:
if float(element) > 2:
total += float(element)
print(lineSplit)
average = total / count
print(average)
break
except (FileNotFoundError):
print("That file does not exist.")
count += 1
filename = input("Enter a file name that exists: ")
averageSpeed()
File contents:
35.2
1.8
65.6
67.9z
70.2
73.2 a3.9 65.6 69.8
6$4.9
54.9
Oops, just fixed my own question with the code below:
def averageSpeed():
count = 0
total = 0
stripLst = 'abcdefghijklmnopqrstuvwxyz$'
while count < 2:
try:
filename = input("Enter a file to process: ")
instance = open(filename, "r")
content = instance.readlines()
for line in content:
print(line)
print()
for line in content:
lineSplit = line.split()
for element in lineSplit:
for letter in element:
for character in stripLst:
if letter == character:
lineSplit.remove(element)
for element in lineSplit:
if float(element) > 2:
total += float(element)
count += 1
print(lineSplit)
average = total / count
print("The total of the speeds of {} excluding all speeds with lettres in them is {}.".format(filename, total))
print("The total number of speeds in {} without letters is {}.".format(filename, count))
print("The average of the speeds of {} excluding all speeds with letters in them is {}.".format(filename, average))
break
except (FileNotFoundError):
print("That file does not exist.")
count += 1
filename = input("Enter a file name that exists: ")
averageSpeed()

Calculate total amount deliveries

For you to solve my problem I think you have to run it on your own. My problem is in this line print(Customer_Name, "has spent", Customers[Customer_Name]['TotalAmount'], "in total")
For you to understand better. For example here, It says Michael has spent 60.0 in total when it should be Michael has spent 20.0 in total
import datetime
import uuid # GET A RANDOM ID FOR THE CUSTOMER
from csv import DictWriter
from datetime import date # GET CURRENT DATE AND TOMORROW DATE
import os
def openFile(): # STARTS HERE
try:
os.startfile('data_entered.csv')
except Exception as e:
print(str(e))
# OPEN FILE WHEN USER(EMPLOYEE) WANTS TO
def closeFile():
try:
os.system('TASKKILL /F /IM notepad.exe')
except Exception as e:
print(str(e)) # ENDS HERE
file = open('CustomerNames.txt', 'a')
file1 = open('Orders_Per_Users.txt', 'a')
file2 = open('data_entered.csv', 'a')
ORDERS_FROM_EMPLOYEE = 0
x = -1
length = 0
Total_Amount = 0.0
Customer_List = []
Address_List = []
My_List = []
today = datetime.date.today()
Today_Key = date.toordinal(date.today())
Today_Date = date.today()
Tomorrow_Date = datetime.date.today() + datetime.timedelta(days=1)
Customers = {}
Dates = {}
print("Welcome to our coffee shop!")
print("Login")
# EMPLOYEE LOGIN PROCESS STARTS
UserLogin = {"Employee1": "coffeeshop1", "Employee2": "coffeeshop2", "Employee3": "coffeeshop3"}
username = password = ''
while True:
username = input("Username: ")
password = input("Password: ")
if (username in UserLogin) and (UserLogin[username] == password):
print("Login Successful")
break
else:
print("Invalid Login. Try again")
# EMPLOYEE LOGIN PROCESS ENDS
# PROCESS AFTER ORDER PLACEMENT STARTS
print("Current Date is: {}".format(Today_Date))
process1 = True
process2 = True
while process1:
while process2:
x += 1
Customer_Name = input("Customer's Name:")
Customer_Address = input("Customer's Address:")
if Customer_Name in Customer_List and Customer_Address in Address_List:
First_Index = Customer_List.index(Customer_Name)
Second_Index = Address_List.index(Customer_Address)
if Customer_Name == Customer_List[First_Index]:
Customer_List.pop(First_Index)
x -= 1
Address_List.append(Customer_Address)
Customer_List.append(Customer_Name)
if Today_Key not in Dates:
Dates[Today_Key] = {}
if Customer_Name not in Dates[Today_Key]:
Dates[Today_Key][Customer_Name] = 1
else:
Dates[Today_Key][Customer_Name] += 1
if Customer_Name in Customers:
Customers[Customer_Name]['Orders'] += 1
Customers[Customer_Name]['TotalAmount'] = Total_Amount
else:
Customers[Customer_Name] = {}
Customers[Customer_Name]['Name'] = Customer_Name
Customers[Customer_Name]['Address'] = Customer_Address
Customers[Customer_Name]['ID'] = uuid.uuid1()
Customers[Customer_Name]['Orders'] = 1
Customers[Customer_Name]['TotalAmount'] = 0
Order_Price = float(input("Total amount of order:"))
ORDERS_FROM_EMPLOYEE += 1
print(Customer_Name, "has ordered {} time(s)".format(Customers[Customer_Name]['Orders']))
Total_Amount = Order_Price + Total_Amount
if Tomorrow_Date == Today_Date: # WHEN THIS IS TRUE, IT MEANS THAT THE DATE CHANGED
print("Total amount of orders today is:{} ".format(Total_Amount)) # NUMBER OF ORDERS IN ONE SPECIFIC DAY
answer1 = input("Send another order? (Y/N)").lower()
if Customers[Customer_Name]['Orders'] == 1:
print("This is the first time", Customer_Name, "orders")
Customers[Customer_Name]['TotalAmount'] = Order_Price
else: # TOTAL AMOUNT OF ALL ORDERS DELIVERED
print(Customer_Name, "has spent", Customers[Customer_Name]['TotalAmount'], "in total")
process2 = answer1 == "y"
LengthCustomersList = len(Customer_List)
length += 1
if int(length) == int(LengthCustomersList):
process1 = False
file1.write(username + " has placed {} orders today".format(ORDERS_FROM_EMPLOYEE))
for i in Customer_List:
file.write(i + '\n')
csv_writer = DictWriter(open('data_entered.csv', 'a'),
fieldnames=['Customer Name', 'Customer Address', 'Customer ID', 'Total Orders',
'Total Amount'])
csv_writer.writeheader()
for customer_name in Customers.keys():
csv_writer.writerows(
[{'Customer Name': Customers[customer_name]['Name'],
'Customer Address': Customers[customer_name]['Address'],
'Customer ID': Customers[customer_name]['ID'],
'Total Orders': Customers[customer_name]['Orders'],
'Total Amount': Customers[customer_name]['TotalAmount']}])
openFile()
file.close()
file1.close()
file2.close()
I have tried adding a Customers[Customer_Name]['Order_Price'] but it did not work
Your issue is with the Total_Amount variable. Its value is kept from the last iteration and assigned to the next customer. You need to retrieve it from your Customers dictionary and then update the value in the dictionary after.
if Customer_Name in Customers:
Customers[Customer_Name]['Orders'] += 1
# Customers[Customer_Name]['TotalAmount'] = Total_Amount # This is where the error was
else:
Customers[Customer_Name] = {}
Customers[Customer_Name]['Name'] = Customer_Name
Customers[Customer_Name]['Address'] = Customer_Address
Customers[Customer_Name]['ID'] = uuid.uuid1()
Customers[Customer_Name]['Orders'] = 1
Customers[Customer_Name]['TotalAmount'] = 0
Total_Amount = Customers[Customer_Name]['TotalAmount'] # retrieve value here
Order_Price = float(input("Total amount of order:"))
ORDERS_FROM_EMPLOYEE += 1
print(Customer_Name, "has ordered {} time(s)".format(Customers[Customer_Name]['Orders']))
Total_Amount = Order_Price + Total_Amount
Customers[Customer_Name]['TotalAmount'] = Total_Amount # update value here

How to find the closest number in CSV file that is the closest to a user input?

I'm still new to Python. I want to make a Car loan calculator that only runs in command prompt. The Calculator needs to take input from the users.
I managed to get the input of the users and print the list of prices in the CSV file. I need to find the closest price in the CSV file that is closest to my variable vehiclecost. Is there any code I can use to do that?
Code:
carlist = open("carlist.csv")
data = carlist.readline()
print("Vehicle cost:")
vehiclecost = float(input().strip("! .? % $"))
print("Annual interest rate:")
AnnualInterestRate = float(input().strip("! .? % $"))
print("Loan duration:")
loandur = int(input().strip("! .? % $"))
while loandur > 10:
print("Try again your loan duration is too long!")
loandur = float(input().strip("! .? % $"))
loanmonth = (loandur * 12)
carwithtax = (vehiclecost * 0.12 + vehiclecost)
InterestRate = AnnualInterestRate / (100 * 12)
monthlypayment = carwithtax * (InterestRate *
((InterestRate + 1)**loanmonth)) / ((InterestRate + 1)**loanmonth - 1)
print("Your loan amount would be: " + str(carwithtax))
print("Your monthly payment would be: {:.2f}".format(monthlypayment))
for x in range(1, loandur + 1):
for y in range(12):
monthlyinterest = (carwithtax * InterestRate)
principal = (monthlypayment - monthlyinterest)
carwithtax = float(carwithtax - principal)
print("Years:", x)
print("Bal remaining: {:.2f}".format(carwithtax))
month = x * 12
print("Total payemtns, {:.2f}".format(month * monthlypayment))
print("Car Recomendation")
for data in carlist:
price = data.split(",")
if int(price[0]) < vehiclecost:
lower = data.split(",")
print(lower)
My input file: Carlist.csv
Snippet
To find the closest value vehicle from the data set:
# get the price list from the csv
price_list = [row[0] for row in car_list]
# get the closest value vehicle
closest_value_vehicle = min(price_list, key=lambda x:abs(int(x)-vehicle_cost))
Full Code
I cleaned up the code a little and added commenting.
Tested with the supplied dataset.
import csv
with open('carlist.csv', 'r') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
# skip header
next(reader, None)
# assign car list
car_list = list(reader)
while True:
try:
# vehicle cost
vehicle_cost = float(input("Please enter the vehicle cost:").strip("! .? % $"))
except ValueError:
print("Invalid input. Vehicle cost must be numeric.")
continue
else:
break
while True:
try:
# annual interest rate
annual_interest_rate = float(input("Please enter the annual interest rate:").strip("! .? % $"))
except ValueError:
print("Invalid input. Annual interest rate must be numeric.")
continue
else:
break
while True:
try:
# loan duration
loan_duration = int(input("Please enter the loan duration:").strip("! .? % $"))
except ValueError:
print("Invalid input. Loan duration must be numeric.")
continue
if loan_duration > 10:
print("Invalid input. Loan duration must be less than 10.")
continue
else:
break
# total loan months
loan_total_months = loan_duration * 12
# vehicle tax
vehicle_tax = vehicle_cost * 0.12 + vehicle_cost
# interest rate
interest_rate = annual_interest_rate / ( 100 * 12 )
# monthly repayment
monthly_repayment = vehicle_tax * ( interest_rate * ( ( interest_rate + 1 ) ** loan_total_months ) ) / ( ( interest_rate + 1 ) ** loan_total_months - 1 )
print("Your loan amount would be: $%s" % str('{:,}'.format(vehicle_tax)) )
print("Your monthly payment would be: {:.2f}".format(monthly_repayment) )
# repayments
for x in range(1, loan_duration + 1):
for y in range(12):
monthly_interest = (vehicle_tax * interest_rate)
principal = (monthly_repayment - monthly_interest)
vehicle_tax = float(vehicle_tax - principal)
print("Years:", x)
print("Balance remaining: ${:.2f}".format(vehicle_tax))
month = x * 12
print("Total payments: ${:.2f}".format(month*monthly_repayment))
# vehicles in price range
vehicles_in_price_range = []
# get the price list from the csv
price_list = [row[0] for row in car_list]
# get the closest value vehicle
closest_value_vehicle = min(price_list, key=lambda x:abs(int(x)-vehicle_cost))
print(closest_value_vehicle)
for row in car_list:
# price
price = row[0]
# check if price in range
if int(price) == int(closest_value_vehicle):
vehicles_in_price_range.append(row)
print("Vehicle Recomendations:")
# print list of vehicles in price range
for vehicle in vehicles_in_price_range:
print('%s %s %s (VIN: %s) (Millage:%s) (Location: %s, %s) - $%s' %
( vehicle[1],
vehicle[6],
vehicle[7],
vehicle[5],
vehicle[2],
vehicle[3],
vehicle[4],
str('{:,}'.format(int(vehicle[0]))) ) )

How to use split() to separate and display a text file to calculate and average

I'm having trouble with the split() function. I have a module named printReport() that contains a name and 3 test scores in each line. I need to split the data so the names and scores can be displayed and have the average calculated. I'm positive I'm trying to do this completely wrong. I'm getting an IndexError: list index out of range. This is only the start of my problem. I still have no idea how to do the calculations and be displayed like below.
Student Name Score 1 Score 2 Score 3 Total
Dave 82 91 77 250
Tom 79 22 84 185
Dick 67 22 91 180
Mon Feb 8 15:12:08 2016
Can someone please explain what I'm doing wrong and how I would fix it.
### Subprogram detStudentData(fn, scores)
def getStudentData(fn, scores):
# Writes instructions for the user to follow
print("Enter the student names and scores following the prompts below.")
print("To finish entering student names, enter: ZZZ.\n")
# Set the flag for the loop
done = False
# Loop to get input from the usere
while done != True:
# Creates a newFile and enables append
newFile = open(fn, "a")
# Asks for a student name and assigns it to student_name
student_name = input("Please enter the student name (ZZZ to finish): ")
# Compairs student_name to see if it is equal to "ZZZ"
if student_name == "ZZZ":
# Sets the flag to True to exit the loop
done = True
# Asks for test scores if student_name is not equal "ZZZ"
else:
# Asks for test score 1 and assigns it to test_1
test_1 = input("Enter score 1: ")
# Asks for test score 2 and assigns it to test_2
test_2 = input("Enter score 2: ")
# Asks for test score 3 and assigns it to test_3
test_3 = input("Enter score 3: ")
print("\n")
newFile.write(student_name) # Writes student_name to newFile
newFile.write(", ") # Writes "," to newFile
newFile.write(test_1) # Writes test_1 to newFile
newFile.write(", ") # Writes "," to newFile
newFile.write(test_2) # Writes test_2e to newFile
newFile.write(", ") # Writes "," to newFile
newFile.write(test_3) # Writes test_3 to newFile
newFile.write("\n") # Wites a return to newFile
# Closes newFile
newFile.close()
# ==============================================================================
### Subprogram getTextFileContents(fn)
def getTextFileContents(fn):
# Opens the file and enables read
with open(fn, "r") as ins:
# Splits the text file before the ","
list = fn.split(",")
# Creates a loop to load the characters into a list
for line in ins:
# Appends the text to list
list.append(line)
# Returns the value in list
return list
# ==============================================================================
### Subprogram printReport(line)
def printReport(line):
# Prints the heading to show the test scores
print("__________________________________________________________")
print("Student Name Score 1 Score 2 Score 3 Total")
print("----------------------------------------------------------")
name = [] # Declare name a list
test1 = [] # Declare test1 a list
test2 = [] # Declare test2 a list
test3 = [] # Declare test a list
with open("grades.txt", "r") as f:
for line in f:
name.append(line.split(",", 1)[0])
line = name[0]
capacity = len(name)
index = 0
while index != capacity:
line = name[index]
for nameOut in line.split():
print(nameOut)
index = index + 1
# ================================================
with open("grades.txt", "r") as f:
for line in f:
test1.append(line.split(",", -1)[1])
line = test1[1]
capacity = len(test1)
index1 = 0
while index1 != capacity:
line = test1[index1]
for t1Out in line.split():
print(t1Out)
index1 = index1 + 1
# ================================================
with open("grades.txt", "r") as f:
for line in f:
test2.append(line.split(",", -1)[2])
line = test2[2]
capacity = len(test2)
index2 = 0
while index2 != capacity:
line = test2[index2]
for t2Out in line.split():
print(t2Out)
index2 = index2 + 1
# ================================================
with open("grades.txt", "r") as f:
for line in f:
test3.append(line.split(" ", -1)[3])
line = test3[3]
capacity = len(test3)
index3 = 0
while index != capacity:
line = test3[index3]
for t3Out in line.split():
print(t3Out)
index3 = index3 + 1
# ==============================================================================
def main():
fn = "grades.txt" # set the working file name
scores = 3 # set the number of scores
getStudentData(fn, scores) # Calls getStudentData()
line = getTextFileContents(fn) # Assigns getTextFileContent() to line
printReport(line) # Calls printReport()
main()
Check the lines
line = test1[1]
line = test2[2]
line = test3[3]
You should start the list from 0, not 1, 2, 3
The offending section is this:
while index != capacity:
line = test3[index3]
for t3Out in line.split():
print(t3Out)
index3 = index3 + 1
The first line should be:
while index3 != capacity:
Note that manually incrementing an index is probably not the best way to loop over a list in Python. A more pythonic way might be something like:
for item in test3:
for t3out in item.split():
print(t3out)
Also, if you're going to stick with incrementing manually, you need to remove the index = index + 1 from inside the for loop. You should only increment after processing each line.
while index != capacity:
line = test3[index3]
for t3Out in line.split():
print(t3Out)
index3 = index3 + 1

Editing a CSV file in python based on an input

I am to create a program that collects data from a csv file, in which is stored item names and stock. I would like to display to the user how much of, for example apple, is in stock.
Item # Item name Item stock Item price
12345670 Apple 20 0.70
What would you like to buy?: 12345670
How much would you like to buy?: 10
And what I'm trying to do is edit the CSV file to display the new figure of 10 since there are 20 apples and the user purchases 10. I have tried various methods but they all give me strange errors.
My expected output would be:
Item # Item name Item stock
12345670 Apple 20
What would you like to buy?: 12345670
How much would you like to buy?: 10
You have bought 10 apple(s) for a price of £7
There are 10 apples left in stock
If the user purchases too many apples:
Item # Item name Item stock
12345670 Apple 20
What would you like to buy?: 12345670
How much would you like to buy?: 30
There are not enough apple(s) in stock to buy that amount
Would you like to buy all there is?: yes
You have bought 20 apple(s) for the price of £14
This is my code
import csv
restart = 10
list1 = []
price = 0
print("Type 'end' to end")
while restart == 10:
file1 = open("CSV File TASK 2.csv", "rt")
file2 = csv.reader(file1)
print(" ")
order = input("Type the item number of your chosen number: ")
if order == 'end':
break
for row in file2:
for field in row:
if order in field:
amount = int(input("How much of that item?: "))
row3 = int(row[3])
if amount > row3:
print("There is not enough of that item in stock")
print("Please try again")
continue
row2 = float(row[2])
row1 = str(row[1])
price = amount * row2 + price
newstock = row3 - amount
print("You have bought {} {}(s) for the price of £{:.2f}".format(amount, row1, price))
print("Your subtotal is currently at {:.2f}".format(price))
receipt = ("{} {} {} {} {}".format(row[0]+" ", row[1], str(amount), "{:10.2f}".format(float(row[2])), "{:10.2f}".format(amount * float(row[2]))))
list1.append(receipt)
print('\n'.join('{}: {}'.format(*k) for k in enumerate(list1)))
Python 3.5.2. Please and thanks in advance.
You could use this:
import csv
f = open('test.csv', 'r') # Here your csv file
r = csv.reader(f)
lines = [l for l in r]
ItemX = 0
Item = input("What would you like to buy? ")
Amount = input("How much would you like to buy? ")
for x in range(len(lines)):
if lines[x][0] == Item:
ItemX = x
else:
continue1 = True # Does nothing
f.close()
fw = open('test.csv', 'w') # Here your csv file
lines[ItemX][2] = float(lines[ItemX][2]) - float(Amount)
writer = csv.writer(fw)
writer.writerows(lines)
fw.close()

Categories

Resources