mysticbaltic
mysticbaltic

Reputation: 31

How would I tell Python to read my text file?

def inputbook():
    question1 = input("Do you want to input book?yes/no:")
    if question1 == "yes":
        author = input("Please input author:")
        bookname = input("Please input book name:")
        isbn = input("Please input ISBN code")
        f = open("books.txt", "a")
        f.write("\n")
        f.write(author )
        f.write(bookname )
        f.write(isbn )
        f.close()
    elif question1 == "no":
        input("Press <enter>")
inputbook();

So I have code like this and I when I write last string (isbn), and I want python to read books.txt file. How am i supposed to do it?

Upvotes: 0

Views: 173

Answers (2)

Steven Almeroth
Steven Almeroth

Reputation: 8202

def inputbook():

    question1 = raw_input("Do you want to input book? (yes/no):")

    if question1 == "yes":
        author = raw_input("Please input author:")
        bookname = raw_input("Please input book name:")
        isbn = raw_input("Please input ISBN code:")
        f = open("books.txt", "a+")
        f.write("%s | %s | %s\n" % (author, bookname, isbn))
        f.close()

    elif question1 == "no":
        raw_input("Press <enter>")
        try:
            print open('books.txt', 'r').read()
        except IOError:
            print 'no book'

if __name__ == '__main__':
    inputbook()

Upvotes: 0

octref
octref

Reputation: 6801

There are problems with your open, which renders it unreadable. You need to open it with:

f = open("books.txt", "+r")

"a" stands for appending, so you won't be able to read books.txt with f.

Second, readlines or readline are not good options for your code as of now. You need to update your write method. Since inside the .txt file, the author, bookname and isbn will be messed together, and you are not able to separate them.

Upvotes: 1

Related Questions