类型错误:'str' 对象不能用 input() 调用

2 python error-handling input

我有以下代码,它应该询问用户 2 文件名。我在第二个函数中的 input() 出现错误,但在第一个函数中没有,我不明白......这是错误:

output = getOutputFile() File "splitRAW.py", line 22, in getOutputFile fileName = input("\t=> ") TypeError: 'str' object is not callable

# Loops until an existing file has been found
def getInputFile():
    print("Which file do you want to split ?")
    fileName = input("\t=> ")
    while 1:
        try:
            file = open(fileName, "r")
            print("Existing file, let's continue !")
            return(fileName)
        except IOError:
            print("No such existing file...")
            print("Which file do you want to split ?")
            fileName = input("\t=> ")

# Gets an output file from user
def getOutputFile():
    print("What name for the output file ?")
    fileName = input("\t=> ")
Run Code Online (Sandbox Code Playgroud)

这是我的 main() :

if __name__ == "__main__":
    input = getInputFile()
    output = getOutputFile()
Run Code Online (Sandbox Code Playgroud)

小智 5

问题是当你说input = getInputFile().

进一步来说:

  1. 程序进入getInputFile()函数,input还没有赋值。这意味着 Python 解释器将使用内置的input,如您所愿。
  2. 你返回filename并离开getInputFile()。解释器现在将名称覆盖input为该字符串。
  3. getOutputFile()现在尝试使用input,但它已被替换为您的文件名字符串。您不能调用字符串,因此解释器会告诉您并抛出错误。

尝试用input = getInputFile()其他一些变量替换,例如fileIn = getInputFile().

此外,您getOutputFile()没有返回任何内容,因此您的output变量将包含None在其中。