Python从文本文件读取用户输入

2024-05-14 13:12:08 发布

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

我在python中读取文本文件时遇到问题。下面将描述我所做的事情和我所做的事情:

此部分用于读取用户输入并将其存储在文本文件bookdata.txt中。这部分没有错误

bookdata = open("bookdata.txt","a")
Author = input("Author's Name: ")
title = input("Book Title: ")
keyword = input("Book Keyword: ")
publisher = input("Publisher: ")
year = input("Year Publish: ")

# write user input into "bookdata.txt"
bookdata.write("Author's Name:    " + Author + "\n")
bookdata.write("Book Title:       " + title + "\n")
bookdata.write("Keyword:          " + keyword + "\n")
bookdata.write("Publisher:        " + publisher + "\n")
bookdata.write("Year Published:   " + year + "\n\n")

bookdata.close() #closes textfile "bookdata.txt"

我的第二个目标是从文本文件bookdata.txt读取用户输入。这是有问题的部分。这是我的密码:

print("************** Search By **************")
print("\t[1] Search By Author")
print("\t[2] Search by Title")
print("\t[3] Search by Keyword")
print("\t[4] Go back")
print("***************************************")
    
searchby = input("Enter Search By Option: ")
if searchby == "1":
   #search author
elif searchby == "2":
   #search title
elif searchby == "3":
   #search keyword
elif searchby == "4":

我不知道如何读取用户输入。例如,如果我按作者搜索,将显示所有相关的用户输入(作者、标题、关键字等)。有人知道这样做的方法吗?先谢谢你


Tags: 用户txtinputsearchtitlekeywordwriteauthor
1条回答
网友
1楼 · 发布于 2024-05-14 13:12:08

在这个场景中,您可以使用一个小技巧来读取作者的姓名、标题、关键字等

所以你的文件有这样的结构

"Author's Name: " 0
"Book Title: "    1
"Book Keyword: "  2
"Publisher: "     3
"Year Publish: "  4
"Author's Name: " 5
"Book Title: "    6
"Book Keyword: "  7
"Publisher: "     8
"Year Publish: "  9
"Author's Name: " 10
"Book Title: "    11
"Book Keyword: "  12
"Publisher: "     13
"Year Publish: "  14

因此,要阅读/搜索所有作者的姓名,我们必须阅读从0开始的行,然后跳过接下来的4行,阅读第5行。并继续跳过接下来的4行以获取下一个作者的姓名

因此,在代码中,我们可以从文件中获取所有作者的姓名


data = myfile.readlines() # Read all Lines from your txt file

authors = data[0::5] # Start from index 0 and and skip next 4 and get value

# Similarly for Titles
titles = data[1::5] # Start from index 1 and skip next 4 and get value

# Keywords
keywords = data[2::5]


# Now to search in authors
if input_author in authors:
    print("Yes Author Exists")

相关问题 更多 >

    热门问题