Home Python - List not printing to outfile
Reply: 1

Python - List not printing to outfile

J Sterls
1#
J Sterls Published in 2017-12-06 15:51:19Z

I'm trying to write a program for checking out/returning books at the library and I'm using temporary lists as storage for all the data in the patrons.txt and books.txt so I can edit it and then put it back in. The problem is that when I try to print the tempBookFile and tempPatronFile to outfile, the "file = outfile" part of following line

print(tempBookFile, file = outfile)

is highlighted in yellow and when I hover over it it says Expected type 'Optional[IO[str]] got 'TextIOWrapper[str]' instead". As a result, everything in the book list and patron list gets deleted, except for the name of the book which is stored in the patron file while it is checked out.

class Book:
    def __init__(self, title, author, genre, isbn):
        self.title = title
        self.author = author
        self.genre = genre
        self.isbn = isbn

    def printAll(self,outfile):
        print(self.title, "|", self.author, "|", self.genre, "|", self.isbn, file = outfile)



class Patron:
    def __init__(self, name, phone, books):
        self.name = name
        self.phone = phone
        self.books = books

    def printAll(self, outfile):
        print(self.name, "|", self.phone, "|", self.books, file = outfile)



def main():
    print("Welcome to JCK library!")
    menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

    while(menu != 6):
        if(menu == 1):
            outfile = open("books.txt", "w")
            title = input("Enter title: ")
            while(title != "done" and title != "Done"):

                author = input("Enter author: ")
                genre = input("Enter genre: ")
                isbn = input("Enter isbn: ")
                book = Book(title,author,genre,isbn)
                book.printAll(outfile)

                print("Book added: ", title)
                print("Author: ", author)
                print("Isbn: ", isbn, "\n")


                title = input("Enter title: ")
            outfile.close()
            menu = eval(input( "Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

        elif(menu == 2):
            outfile = open("patrons.txt", "w")
            name = input("Enter patron name: ")
            phone = input("Enter phone number: ")
            books = []

            patron = Patron(name,phone,books)
            patron.printAll(outfile)
            outfile.close()
            menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

        elif(menu == 3):
            title = ""
            author = ""
            genre = ""
            isbn = ""
            name = ""
            phone = ""
            books = []
            outfile = open("patrons.txt", "r")
            patronName = input("Enter Patron Name: ")

            if (patronName in outfile.read()):
                print("Patron found.")

                for line in outfile.readlines():
                    if(patronName in line):
                        patronInfo = line.split("|")
                        name = patronInfo[0]
                        phone = patronInfo[1]
                        books = patronInfo[2]

                #Creates a temporary list containing all of the contents of the patrons.txt file so that
                #the list can be modified and then put back into the patrons.txt file
                tempPatronFile = outfile.readlines()

                #Removes the line from the temporary list that contains information about the patron who is checking out
                #a book so that it can be re-added to the list after it is updated
                for line in tempPatronFile:
                    if(patronName in line):
                        tempPatronFile.pop(line)

                outfile.close()
                outfile = open("books.txt", "r")
                bookName = input("Enter Book Name: ")

                if bookName in outfile.read():
                    books.append(bookName)

                    for line in outfile.readlines():
                        if(bookName in line):
                            bookInfo = line.split("|")
                            title = bookInfo[0]
                            author = bookInfo[1]
                            genre = bookInfo[2]
                            isbn = bookInfo[3]

                    book = Book(title,author,genre,isbn)

                    #Creates a temporary list containing all of the contents of the books.txt file so that
                    #the list can be modified and then put back into the books.txt file
                    tempBookFile = outfile.readlines()

                    #Removes the line from the temporary list that contains information about the book so that
                    #the book can be re-added later after it has been returned.
                    for line in tempBookFile:
                        if(bookName in line):
                            tempBookFile.pop(line)

                    outfile.close()

                    outfile = open("books.txt", "w")
                    print(tempBookFile, file = outfile)
                    outfile.close()

                    outfile = open("patrons.txt", "w")
                    print(tempPatronFile, file = outfile)
                    patron = Patron(name,phone,books)
                    patron.printAll(outfile)
                    book.printAll(outfile)
                    outfile.close()

                    print("Book due in 2 weeks.")

            menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

        elif(menu == 4):
            outfile = open("patrons.txt", "r")
            patronName = input("Enter patron name: ")


            if(patronName in outfile.read()):
                for line in outfile.readlines():
                    if(patronName in line):
                        patronInfo = line.split("|")
                name = patronInfo[0]
                phone = patronInfo[1]
                books = patronInfo[2]

                bookName = input("Enter book name: ")

                if(bookName in outfile.read()):
                    for line in outfile.readlines():
                        if(bookName in line):
                            bookInfo = line.split("|")
                        title = bookInfo[0]
                        author = bookInfo[1]
                        genre = bookInfo[2]
                        isbn = bookInfo[3]

                    book = Book(title, author, genre, isbn)

                # Creates a temporary list containing all of the contents of the patrons.txt file so that
                # the list can be modified and then put back into the patrons.txt file
                tempPatronFile = outfile.readlines()

                # Removes the line from the temporary list that contains information about the patron who is checking out
                # a book so that it can be re-added to the list after it is updated
                for line in tempPatronFile:
                    if (patronName in line):
                        tempPatronFile.pop(line)

                #Removes the information about the book which was stored in the patron file while it was checked out.
                #Upon being returned, the book will go back into the books.txt file
                for line in tempPatronFile:
                    if(bookName in line):
                        tempPatronFile.pop(line)


                outfile.close()

                outfile = open("books.txt", "r")
                tempBookFile = outfile.readlines()
                tempBookFile.append(book)###################################
                outfile.close()

                outfile = open("books.txt", "w")
                print(tempBookFile, file = outfile)
                outfile.close()

                outfile = open("patrons.txt", "w")
                for line in books:
                    if(bookName in line):
                        books.pop(line)
                patron = Patron(name,phone,books)
                print(tempPatronFile, file = outfile)
                patron.printAll(outfile)
                outfile.close()
                print("Book returned.")

            menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

        elif(menu == 5):
            outfile = open("patrons.txt", "r")
            patronName = input("Input patron's name: ")

            if(patronName in outfile.read()):
                for line in outfile.readlines():
                    if(patronName in line):
                        patronInfo = line.split("|")
                name = patronInfo[0]
                phone = patronInfo[1]
                books = patronInfo[2]

                print(patronName, "has the following book(s) checked out:\n", books)

            menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))


    print("Have a nice day!")


main()
Nick Chapman
2#
Nick Chapman Reply to 2017-12-06 15:56:42Z

The issue has to do with your old school file opening. You should avoid using open and close to manage your files and instead use a with statement. Most of the time if you are using resources that need to be cleaned up/managed you should use

with open("my_file.txt", "w") as output_file:
    # File based operations here

And then PyCharm will be happy. You can see a similar problem here: PyCharm - Expected type 'Optional[IO[str]]', got 'TextIOWrapper[str]' instead

Also as someone commented (it's now deleted) make sure you are opening the file in the correct mode. "w" will erase everything in the file and let you write to it. "r" will only let you read from it. "a" will let you append to the file and might be what you want. If you look up the inputs to open you can get the full details. https://docs.python.org/3/library/functions.html#open

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.301162 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO