试图找出如何从文本文件中读取和写入数组

时间:2017-05-07 23:10:17

标签: python python-2.7

此代码是我正在制作的销售点的一部分。

我正在尝试弄清楚如何从文本文件中填充bookInventorygameInventory数组,并在我进行更改后让数组中的元素写入文本文件。

如果我可以删除保存在文本文件中的数组元素,也会有所帮助。我仍然是编码和python的新手,但到目前为止确实有了不错的理解,但是非常感谢任何帮助。

这是我的尝试:

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

1 个答案:

答案 0 :(得分:0)

你可以这样做:

with open("books.txt") as file:
    lines = file.readlines()
    for item in lines:
        bookInventory[len(bookInventory)-1] = item

gameInventory相同:

with open("games.txt") as file:
    lines = file.readlines()
    for item in lines:
        gameInventory[len(gameInventory)-1] = item