Python - 列表不打印到outfile

时间:2017-12-06 15:51:19

标签: python list class file-io

我正在尝试编写一个用于在图书馆检查/退回书籍的程序,我正在使用临时列表作为patrons.txt和books.txt中所有数据的存储空间,因此我可以编辑它然后放入它回来了。问题是,当我尝试将tempBookFile和tempPatronFile打印到outfile时,以下行的“file = outfile”部分

print(tempBookFile, file = outfile)

以黄色突出显示,当我将鼠标悬停在它上面时会显示Expected type 'Optional[IO[str]] got 'TextIOWrapper[str]' instead"。因此,书籍列表和顾客列表中的所有内容都将被删除,但在签出时存储在顾客文件中的书籍名称除外。

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

1 个答案:

答案 0 :(得分:0)

问题与您的旧学校档案开放有关。您应该避免使用openclose来管理文件,而是使用with语句。大多数情况下,如果您使用的资源需要清理/管理,您应该使用

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

然后PyCharm会很高兴。您可以在此处看到类似的问题:PyCharm - Expected type 'Optional[IO[str]]', got 'TextIOWrapper[str]' instead

另外,当有人评论(现在已删除)时,请确保以正确的模式打开文件。 "w"将清除文件中的所有内容并让您写入文件。 "r"只会让您从中读取。 "a"将允许您附加到该文件,可能是您想要的。如果您查看open的输入,您可以获得完整的详细信息。 https://docs.python.org/3/library/functions.html#open