I'm facing a problem where I can't finish my code. There is a problem where upon running this code it comes up as an IndexError.
name = str(input("Please input the books name that you would like to borrow: ")
file = open("books.txt", "r")
file_contents = []
for line in file:
stripped_line = line.strip()
line_list = stripped_line.split()
file_contents.append(line_list)
file.close()
i = 0
for name in range(len(file_contents)):
i = i +1
if name == file_contents[i]:
table_3= [["Borrow Book","1"],
["Cancel Borrowing","2"]]
headers_3 = ["Details", "No."]
print(tabulate(table_3, headers_3, tablefmt = "grid"))
num = int(input("Please input 1 for confirmation of booking and 2 for canceling the booking: "))
file_contents[i] = changed_name
changed_name = str(changed_name)
if name == file_contents[i]:
IndexError: list index out of range
Example Of The File:
(books.txt)
Exile
Dancing In The Moonlight
Here is your complete solution . I hope it would help You
from tabulate import tabulate
name = str(input("Please input the books name that you would like to borrow: "))
file = open("books.txt", "r")
file_contents = [] #available books
for line in file:
line=line.strip()
file_contents.append(line)
file.close()
print("file content: ",file_contents)
i = 0
if name in file_contents:
table_3= [["Borrow Book","1"],["Cancel Borrowing","2"]]
headers_3 = ["Details", "No."]
print(tabulate(table_3, headers_3, tablefmt = "grid"))
num = int(input("Please input 1 for confirmation of booking and 2 for canceling the booking: "))
if(num==1):
try:
#user wants to withdraw that books so we've to remove that book from our available list of books
file_contents.remove(name)
#now we remove that book name from our available books.txt file
file=open("books.txt","w")
str1=" "
str1.join(file_contents)
file.write(str1)
print("Happy to serve you :-) visit again for more good books")
except Exception as e:
print("There is an error ",e)
else:
print("visit again for more good books")