python


trying to figure out how to have my arrays read and write from a text file


This code is part of a point of sale I am making.
I am trying to figure out how to fill my bookInventory and gameInventory arrays from a text file and also have the elements in the array write to the text file after I have made changes.
It would also help if I could delete elements of the array that are saved in the text file. I am still really new to coding and python but do have a decent understanding so far but any help is greatly appreciated.
This is my attempt:
def sell_Game_Menu():
os.system("CLS")
print ("Scruffy Nerf Herders' Books and Games:\n")
print("\nWhich game would you like to sell?")
addGame = 'y'
while addGame == 'y':
for i in range(len(gameInventory)):
print("\n%i- Title: %s \n Arthur: %s \n Price: $%.2f" % (i+1, gameInventory[i][0],gameInventory[i][1],gameInventory[i][2]))
gameSold = input()
sellGameTemp.append(gameInventory[gameSold-1])
howManyGame= input("You chose, %s: How many?" % gameInventory[gameSold-1][0])
addGame = raw_input("Would you like to sell another one? 'Y' or 'N' ").lower()
quantityGame.append(howManyGame)
if addGame == 'y':
for i in range(len(gameInventory)):
print("\n%i- Title: %s \n Arthur: %s \n Price: $%.2f" % (i+1, gameInventory[i][0],gameInventory[i][1],gameInventory[i][2]))
gameSold = input()
sellGameTemp.append(gameInventory[gameSold-1])
howManyGame= input("You chose, %s: How many?" % gameInventory[gameSold-1][0])
addGame = raw_input("Would you like to sell another one? 'Y' 'N' ").lower()
quantityGame.append(howManyGame)
else:
break
#creating the menu for selling a book using an array inside an array
def sell_Book_Menu():
howMany = int
os.system("CLS")
print ("Scruffy Nerf Herders' Books and Games:\n")
print("\nWhich book would you like to sell?")
addBook = 'y'
while addBook == 'y':
for i in range(len(bookInventory)):
print("\n%i- Title: %s \n Arthur: %s \n Price: $%.2f" % (i+1, bookInventory[i][0],bookInventory[i][1],bookInventory[i][2]))
bookSold = input()
sellBookTemp.append(bookInventory[bookSold-1])
howManyBook = input("You chose, %s: How many?" % bookInventory[bookSold-1][0])
quantityBook.append(howManyBook)
#sellBookTemp.append(howManyBook= input("You chose, %s: How many?" % bookInventory[bookSold-1][0]))
addBook = raw_input("Would you like to sell another one? 'Y' or 'N' ").lower()
if addBook == 'y':
for i in range(len(bookInventory)):
print("\n%i- Title: %s \n Arthur: %s \n Price: $%.2f" % (i+1, bookInventory[i][0],bookInventory[i][1],bookInventory[i][2]))
bookSold = input()
sellBookTemp.append(bookInventory[bookSold-1])
howManyBook = input("You chose, %s: How many?" % bookInventory[bookSold-1][0])
quantityBook.append(howManyBook)
#sellBookTemp.append(howManyBook= input("You chose, %s: How many?" % bookInventory[bookSold-1][0]))
addBook = raw_input("Would you like to sell another one? 'Y' or 'N' ").lower()
else:
break
#creating the main menu
def main_Menu():
print ("Scruffy Nerf Herders' Books and Games:\n")
choice = input("1. Cashier Mode.\n2. Self Checkout Mode.")
while True:
if choice == 1:
cashier_Menu_List()
elif choice == 2:
self_Checkout_Menu_List()
else:
print ("\n Not a Valid choice try AGAIN.")
time.sleep(2)
os.system("CLS")
#function to create the cashier menu
def cashier_Menu():
os.system("CLS")
print ("Scruffy Nerf Herders' Books and Games:\n")
print ("1. Sell a book.\n2. Sell a game\n3. Add a book to inventory.\n4. Add a game to inventory.\n5. Delete book from inventory.\n6. Delete game from inventory.\n7. Show all inventory.\n8. Show book inventory.\n9. Show game inventory.\n10. Show Shopping Cart.\n11. Checkout.")
return input()
#checking against input from cashier_Menu to figure out which function to call
def cashier_Menu_List():
while True:
os.system("CLS")
choice = cashier_Menu()
if choice == 1:
sell_Book_Menu()
elif choice == 2:
sell_Game_Menu()
elif choice == 3:
add_Book()
elif choice == 4:
add_Game()
elif choice == 5:
delete_Book()
elif choice == 6:
delete_Game()
elif choice == 7:
show_All_Inventory()
elif choice == 8:
show_Book_Inventory()
elif choice == 9:
show_Game_Inventory()
elif choice == 10:
show_Cart()
elif choice == 11:
cart()
else:
print ("\n Not a valid choice try AGAIN.")
time.sleep(2)
os.system("CLS")
def show_All_Inventory():
os.system("CLS")
leave = 'n'
print ("Scruffy Nerf Herders' Books and Games:\n")
if leave == 'n':
print ("\nBook Inventory:")
for i in range(len(bookInventory)):
print ("\n%i- Title: %s \n Author: %s \n Price: $%.2f" % (i+1, bookInventory[i][0],bookInventory[i][1],bookInventory[i][2]))
print ("\n\nGame Inventory:")
for i in range(len(gameInventory)):
print("\n%i- Title: %s \n Author: %s \n Price: $%.2f" % (i+1, gameInventory[i][0],gameInventory[i][1],gameInventory[i][2]))
leave = raw_input("\nPress enter for main menu")
#showing just the book inventory
def show_Book_Inventory():
os.system("CLS")
leave = 'n'
print ("Scruffy Nerf Herders' Books and Games:\n")
if leave == 'n':
print ("\nBook Inventory:")
for i in range(len(bookInventory)):
print ("\n%i- Title: %s \n Author: %s \n Price: $%.2f" % (i+1, bookInventory[i][0],bookInventory[i][1],bookInventory[i][2]))
leave = raw_input("\nPress enter for main menu")
#this is showing just the game inventory
def show_Game_Inventory():
os.system("CLS")
leave = 'n'
print ("Scruffy Nerf Herders' Books and Games:\n")
if leave == 'n':
print ("\n\nGame Inventory:")
for i in range(len(gameInventory)):
print("\n%i- Title: %s \n Developer: %s \n Price: $%.2f" % (i+1, gameInventory[i][0],gameInventory[i][1],gameInventory[i][2]))
leave = raw_input("\nPress enter for main menu")
#maiking a newBook array and appending varibles to it and appending bookInventory with the newBook array to add a new book entry
def add_Book():
os.system("CLS")
addNewBook = 'y'
while addNewBook == 'y':
print ("Scruffy Nerf Herders' Books and Games:\n\n\n")
print ("Add Book: \n")
title = raw_input("What is the title? ")
arthur = raw_input("What is the authors name? ")
price = input("What is the sell price of the book? ")
newBook = []
newBook.append(title)
newBook.append(arthur)
newBook.append(price)
bookInventory.append(newBook)
addNewBook = raw_input("Would you like to add another book: 'Y' 'N'? ").lower()
if addNewBook == 'y':
title = raw_input("What is the title? ")
arthur = raw_input("What is the authors name? ")
price = input("What is the sell price of the book? ")
newBook = []
newBook.append(title)
newBook.append(arthur)
newBook.append(price)
bookInventory.append(newBook)
addNewBook = raw_input("Would you like to add another book?: 'Y' 'N' ").lower()
else:
break
#maiking a newGame array and appending varibles to it and appending gameInventory with the newgame array to add a new game entry
def add_Game():
addNewGame = 'y'
while addNewGame == 'y':
print ("Scruffy Nerf Herders' Books and Games:\n\n\n")
print ("Add Game: \n")
title = raw_input("What is the title? ")
arthur = raw_input("What is the developers name? ")
price = input("What is the sell price of the book? ")
newGame = []
newGame.append(title)
newGame.append(arthur)
newGame.append(price)
gameInventory.append(newGame)
addNewGame = raw_input("Would you like to add another game: 'Y' 'N:? ").lower()
if addNewGame == 'y':
title = raw_input("What is the title? ")
arthur = raw_input("What is the developers name? ")
price = input("What is the sell price of the book? ")
newGame = []
newGame.append(title)
newGame.append(arthur)
newGame.append(price)
gameInventory.append(newGame)
addNewGame = raw_input("Would you like to add another game: 'Y' 'N'? ").lower()
else:
break
#deleting a Book from the inventory by using an index stored in deleteBook
def delete_Book():
deleteNewBook = 'y'
bookDelete = []
while deleteNewBook == 'y':
print ("Scruffy Nerf Herders' Books and Games:\n")
print ("Pick a book to delete from inventory")
for i in range(len(bookInventory)):
print ("\n%i- Title: %s \n Author: %s \n Price: $%.2f" % (i+1, bookInventory[i][0],bookInventory[i][1],bookInventory[i][2]))
deleteBook = input()
bookDelete.append(bookInventory[deleteBook-1])
del bookInventory[deleteBook-1]
deleteNewBook = raw_input("\nDo you want to delete another book: 'Y' 'N'? ").lower()
if deleteNewBook == 'y':
for i in range(len(bookInventory)):
print ("\n%i- Title: %s \n Author: %s \n Price: $%.2f" % (i+1, bookInventory[i][0],bookInventory[i][1],bookInventory[i][2]))
deleteBook = input()
bookDelete.append(bookInventory[deleteBook-1])
del bookInventory[deleteBook-1]
deleteNewBook = raw_input("\nDo you want to delete another book: 'Y' 'N'? ").lower()
else:
break
#deleting a game from the inventory by using an index stored in deleteGame
def delete_Game():
deleteNewGame = 'y'
gameDelete = []
while deleteNewGame == 'y':
print ("Scruffy Nerf Herders' Books and Games:\n")
print ("Pick a game to delete from inventory")
for i in range(len(gameInventory)):
print ("\n%i- Title: %s \n Developer: %s \n Price: $%.2f" % (i+1, gameInventory[i][0],gameInventory[i][1],gameInventory[i][2]))
deleteGame = input()
gameDelete.append(gameInventory[deleteGame-1])
del gameInventory[deleteGame-1]
deleteNewGame = raw_input("\nDo you want to delete another game: 'Y' 'N'? ").lower()
if deleteNewGame == 'y':
for i in range(len(gameInventory)):
print ("\n%i- Title: %s \n Developer: %s \n Price: $%.2f" % (i+1, gameInventory[i][0],gameInventory[i][1],gameInventory[i][2]))
deleteGame = input()
gameDelete.append(gameInventory[deleteGame-1])
del gameInventory[deleteGame-1]
deleteNewGame = raw_input("\nDo you want to delete another game: 'Y' 'N'? ").lower()
else:
break
#function for main that checks choice and calls functions
def main():
main_Menu()
#start of program importing different libraries
import time
import os
import sys
#creating the arrays
bookInventory = [["Welcome to programmning","Kirsten",15.95],["Python for Beginners","Kirsten",12.55],["(Part1)Harry Potter and The Deathly Hallows", "J.K. Rowling",16.45],["How to Pass Finals", "Me", 26.25]]
gameInventory = [["Battlefield 1942", "EA DICE",15.50],["Battefield 2", "EA DICE", 12.30],["Battlefied: Bad Company", "EA DICE", 21.50]]
#trying to use text file here
'''with open("books.txt") as file:
bookInventory = file.readlines()
with open("games.txt") as file:
gameInventory = file.readlines()'''
newBookInventory =[]
newGameInventory = []
sellBookTemp = []
sellGameTemp = []
quantityBook = []
quantityGame = []
#calling function main
main()
You could do:
with open("books.txt") as file:
lines = file.readlines()
for item in lines:
bookInventory[len(bookInventory)-1] = item
and the same for gameInventory:
with open("games.txt") as file:
lines = file.readlines()
for item in lines:
gameInventory[len(gameInventory)-1] = item

Related Links

Python HTMLParser - stop parsing
Interactive menu based exe in Python
How to get the rect() of a dynamic circle
Building logic gates
Return all tuple only from list
Reassign rows and columns in Python csv
How to check raw_input answers inside if-statements
how does one define a nullary function in python?
Sympy, plotting geometric entities yields either ImportError: no module named 'plot' or AttributeError: 'Circle' object has no attribute 'is_3D'
Select first row that meets certain condition
Splitting longer patterns using regex without losing characters Python 3+
Using python sdist to create a package that includes generated files in the build directory
Any elegant way to add a method to an existing object in python?
Setting cookies for static files using bottle.py
Python/Feedparser: reading RSS feed fails
How to generate a Torrent Magnet URI from a directory?

Categories

HOME
sas
ssas-2012
checkbox
mapping
performancecounter
webrtc
windows-7
jasmine
thunderbird-addon
actionscript
laravel-5.2
mainframe
wampserver
adsense
mongodb-query
phoenix
eclipse-luna
r-lavaan
phpbb
pyephem
google-people
android-fragmentactivity
cython
tortoisegit
sonarqube-msbuild-runner
rails-activerecord
thingsboard
spring-ws
nmf
auditing
cep
solidworks
vertex-buffer
lmdb
shapes
hashcat
pace
color-scheme
broadleaf-commerce
android-download-manager
rule
stdclass
lftp
email-parsing
vcf
w3-total-cache
defold
multi-agent
scd
pagefile
launch
paas
keycode
verbose
nsfetchedresultscontrolle
hspec
windows-azure-pack
picasa
galleriffic
shipitjs
spatial-query
usb-drive
fortran90
drf-nested-routers
textkit
paypal-nvp
calibration
ffprobe
orientation-changes
gmaps4rails
qtestlib
suffix-array
method-overriding
csplit
mfmailcomposeviewcontroll
funkload
help-viewer
chrome-for-android
cling
real-time-updates
nservicebus4
trimming
backbone-relational
surveyor-gem
client-side-scripting
grunt-contrib-compass
fraud-prevention
graph-coloring
pascals-triangle
getusermedia
parameterization
isolatedstorage
electronic-signature
coff
posting
port-scanning
file-encodings
graph-layout
callgrind
evb

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App