Python function takes previous value even though new one is given through input

I am working on a library management system project, where there are two text files “books.txt” and “borrowers.txt”. Every time someone borrows a book, the quantity of book is decreased by one in “books.txt”

This is my books.txt file:

1,Harry Potter,JK Rowling,30,$2,11
2,Start With Why,Simon Sinek,8,$1.5,8
3,Programming With Python,John Smith,20,$1.5,8

The first column consists of course ID and the last one is the quantity.

This is the function(stored in a separate file: “change”) which replaces the quantity string.

def inplace_change(filename, old_string, new_string):
    # Safely read the input filename using 'with'
    with open(filename) as f:
        s = f.read()
        if old_string not in s:
            print('"{old_string}" not found in {filename}.'.format(**locals()))
            return

    # Safely write the changed content, if found in the file
    with open(filename, 'w') as f:
        print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
        s = s.replace(old_string, new_string)
        f.write(s)

and this is the function which lets users actually borrow the file from the library:

import change

with open('books.txt') as textFile:
    list1 = [line.strip().split(',') for line in textFile]
    print(list1)

dict = {}
    
def main_borrow():                   
    borrowerName = input("Enter your name: ").lower()
    bookID = input("Enter the required book ID: ")
    bookIDFound = False
    for i in range(len(list1)):
                for j in range(5):
                    if bookID == list1[i][0]:
                        bookIDFound = True
                        requestedBookID = bookID
                        print("The requested book is", list1[i])
                        dict1 = {borrowerName : list1[i][1]}
                        dString = repr(dict1)
                        f = open('borrowers.txt', 'a')
                        f.write(dString + 'n')
                        f.close()
                        nowAvailable = int(list1[i][5]) - 1
                        nowAvailableStr = str(nowAvailable)
                        print(nowAvailable)

                        change.inplace_change('books.txt', list1[i][5], nowAvailableStr)
                        
                        f.close()
                    break
    if bookIDFound == False:
        print("Enter a valid book ID: ")

This is the main file:

import borrow
print("Welcome to library management systemn")



def borrow1():
    print("nYou wil now borrow a bookn")
    borrow.main_borrow()

def return1():
    print("nYou will now return a bookn")

def exit():
    print("nThank you for using our Library Management Systemn")

while True:
    a = int(input("Enter '1' to borrow a book nEnter '2' to return a book nEnter '3' to exit nPlease enter a value: "))
    if a == 1:
        borrow1()
    elif a == 2:
        return1()
    else:
        exit()
        break

Now the problem I am facing is, the program works fine, the first time i borrow a book, when i borrow it the second time under a different name, it says it cant find the string like this:

Enter '1' to borrow a book 
Enter '2' to return a book 
Enter '3' to exit 
Please enter a value: 1

You wil now borrow a book

Enter your name: Rojin Dumre
Enter the required book ID: 1
The requested book is ['1', 'Harry Potter', 'JK Rowling', '30', '$2', '10']
9
Changing "10" to "9" in books.txt
Enter '1' to borrow a book 
Enter '2' to return a book 
Enter '3' to exit 
Please enter a value: 1

You wil now borrow a book

Enter your name: Jetsun Drolma
Enter the required book ID: 1
The requested book is ['1', 'Harry Potter', 'JK Rowling', '30', '$2', '10']
9
"10" not found in books.txt.
Enter '1' to borrow a book 
Enter '2' to return a book 
Enter '3' to exit 
Please enter a value: 

I have been trying for some 2 hours now, I cant figure it out. Also, please suggest me a better way to replace the string because if two books have the same quantity in books.txt file, the function replaces both quantities. Thank you!

Answer

The problem is you are reading the file only once.
After updating the contents of the file, you need to read it again to get the latest contents.

You can do so by moving the file reading code to main_borrow()

def main_borrow():
    with open('books.txt') as textFile:
        list1 = [line.strip().split(',') for line in textFile]
        print(list1)

As for changing the quantity only for the borrowed book, use the built-in fileinput module.

import fileinput


def inplace_change(filename, book_id, old_string, new_string):
    for line in fileinput.input(files=filename, inplace=True):
        list = line.strip().split(',')
        if list[0] == book_id:
            list[5] = new_string
        print(','.join(list))

    fileinput.close()

And change call to inplace_change

inplace_change('books.txt', list1[i][0], list1[i][5], nowAvailableStr)

Here’s a refactored version of main_borrow

def main_borrow():
    with open('books.txt') as textFile:
        lines = textFile.readlines()

    borrowerName = input("Enter your name: ").lower()
    bookID = input("Enter the required book ID: ")
    bookIDFound = False
    for line in lines:
        list = line.strip().split(',')
        if bookID == line[0]:
            bookIDFound = True
            requestedBookID = bookID
            print("The requested book is", list)
            dict1 = {borrowerName: list[1]}
            dString = repr(dict1)
            f = open('borrowers.txt', 'a')
            f.write(dString + 'n')
            f.close()
            nowAvailable = int(list[5]) - 1
            nowAvailableStr = str(nowAvailable)
            inplace_change('books.txt', list[0], list[5], nowAvailableStr)

            f.close()
            break

    if bookIDFound == False:
        print("Enter a valid book ID: ")