“io.TextIOWrapper”对象不可调用Python中的错误

sdnqo3pr  于 2023-02-07  发布在  Python
关注(0)|答案(1)|浏览(214)

尝试创建一个库存管理系统的大学作业。目前试图删除一行由用户指定的关键字从一个文本文件,并返回到主菜单一旦完成,但我遇到这个错误时,返回到菜单,指定的行被删除,从文本文件,尽管错误。

# Remove an item from inventory
   elif mainMenuInput == 3:
        print("\n\nR E M O V E    I T E M")
        print("-------------------------------------------------------")
        eraseItemName = str(input("Enter the item name to be removed & Press Enter to continue: "))

        # Erases line with chosen word from inventory.txt
        with open("inventory.txt", "r") as input:
            with open("sample.txt", "w") as output:
                for line in input:
                    if not line.strip("\n").startswith(eraseItemName):
                        output.write(line)

        os.replace("sample.txt", "inventory.txt")
        
        # Creates String for transaction report and writes it to transactionReport.txt
        timeLog = datetime.datetime.now()
        timeLogStr = str(timeLog)
        reportStringErase = "\n- Removed " + eraseItemName + " item at: " + timeLogStr
        report = open("transactionReport.txt","a")
        report.write(reportStringErase)
        report.close()
        
        print("-------------------------------------------------------")
        print("Item quantity successfully removed!\n")
        print("\n")
        mainMenu()
        mainMenuInput = int(input("\n Enter a choice & Press ENTER to continue[1-5]: "))

python shell 中显示错误:

mainMenuInput = int(input("\n Enter a choice & Press ENTER to continue[1-5]: "))
TypeError: '_io.TextIOWrapper' object is not callable
roejwanj

roejwanj1#

在代码的早期,您可以:

with open("inventory.txt", "r") as input:

以后你会:

mainMenuInput = int(input("\n Enter a choice & Press ENTER to continue[1-5]: "))

第一行创建了一个名为input的全局变量(假设您显然是在全局范围内操作),它隐藏了内置变量名input,因此当您稍后尝试使用input作为内置变量时,您最终会“调用”file对象。
保持名称独立,或者(如果必须)在with块之后放置del input,以便从全局范围中删除隐藏变量。

相关问题