如何告诉Python读取我的文本文件?

2024-10-04 03:29:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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读书籍.txt文件。我该怎么做?在


Tags: notxtyouinputdefdoyeswrite
2条回答
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()

你的open有问题,这使得它无法阅读。 您需要打开它:

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

“a”代表附加,所以你不能阅读书籍.txt与f

第二,readline或readline不是目前代码的好选择。你需要更新你的写方法。因为在.txt文件中,author、bookname和isbn将被混在一起,而您无法将它们分开。在

相关问题 更多 >