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

所以我有这样的代码,当我写最后一个字符串(isbn)时,我想让python读取books.txt文件。我该怎么做?

4

2 回答 2

1

您的打开有问题,导致它无法阅读。您需要使用以下命令打开它:

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

“a”代表追加,所以你将无法阅读带有 f 的 books.txt。

其次,到目前为止,readlines 或 readline 不是您的代码的好选择。您需要更新您的写入方法。由于在 .txt 文件中,作者、书名和 isbn 将被混淆在一起,您无法将它们分开。

于 2013-03-11T16:08:36.527 回答
0
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()
于 2013-03-11T16:14:38.310 回答