[英]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. 所以我有这样的代码,当我写最后一个字符串(isbn)时,我想让python读取books.txt文件。 How am i supposed to do it?
我应该怎么做?
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. “ a”代表追加,因此您将无法使用f读取books.txt。
Second, readlines or readline are not good options for your code as of now. 其次,到目前为止,对于您的代码而言,readlines或readline并不是很好的选择。 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.
由于在.txt文件中,作者,书名和isbn会被弄乱,因此您无法将它们分开。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.