seenchan
seenchan

Reputation: 9

Python reading user input from a textfile

I have a problem in reading the text files in python. Below will describe things that im doing and what im stuck at:

This part functions to read user input and store it inside the textfile bookdata.txt. This part have no error in it.

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"

My second objective is to read the user input from the textfile bookdata.txt. This is the problematic part. Here is my code:

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":

i dont know how to read user input. For example, If i search by author, all of the related user input (author, title, keyword, etc...) will show. Does anyone know any method for doing this? Thank you in advance.

Upvotes: 0

Views: 310

Answers (1)

glory9211
glory9211

Reputation: 843

In this scenario you can use a small trick to read the Author's name, Title, Keyword etc.

So your file has a structure like this

"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

So to Read/Search all the Author's Name we have to read the lines starting from 0, then skip next 4 lines and read 5th line. And continue skipping next 4 lines to get the next Author's Name.

So in code to get all Author's Name from the file we can use


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")

Upvotes: 1

Related Questions