Python函数接受以前的值,即使新值是通过输入给出的

2024-09-27 07:31:27 发布

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

我正在从事一个图书馆管理系统项目,其中有两个文本文件“books.txt”和“bookers.txt”。每次有人借一本书,“books.txt”中的书的数量就会减少一本

这是my books.txt文件:

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

第一列由课程ID组成,最后一列是数量

这是替换数量字符串的函数(存储在单独的文件:“change”中)

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)

这是一个允许用户从库中实际借用文件的功能:

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

这是主文件:

import borrow
print("Welcome to library management system\n")



def borrow1():
    print("\nYou wil now borrow a book\n")
    borrow.main_borrow()

def return1():
    print("\nYou will now return a book\n")

def exit():
    print("\nThank you for using our Library Management System\n")

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

现在我面临的问题是,这个程序运行得很好,我第一次借书,第二次用不同的名字借书时,它说找不到这样的字符串:

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: 

我已经试了两个小时了,我想不出来。另外,请建议更好的替换字符串的方法,因为如果books.txt文件中两本书的数量相同,则函数将替换这两个数量。谢谢大家!


Tags: thetointxt数量stringreturnexit
1条回答
网友
1楼 · 发布于 2024-09-27 07:31:27

问题是您只读取了一次文件。
更新文件内容后,需要再次读取以获取最新内容

您可以通过将文件读取代码移动到main_borrow()来执行此操作

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

至于仅更改借阅图书的数量,请使用内置的fileinput模块

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

并将调用更改为inplace_change-

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

这里是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: ")

相关问题 更多 >

    热门问题