简体   繁体   English

TypeError:“ str”对象无法通过input()调用

[英]TypeError: 'str' object is not callable with input()

I have the following code, which is supposed to ask the user 2 file names. 我有以下代码,应该询问用户2文件名。 I get an error with the input() in the second function but not in the first, I don't understand... Here is the error : 我在第二个函数中遇到了input()的错误,但在第一个函数中却没有,我不明白...这是错误:

output = getOutputFile() File "splitRAW.py", line 22, in getOutputFile fileName = input("\\t=> ") TypeError: 'str' object is not callable 输出= getOutputFile()在getOutputFile中的文件“ splitRAW.py”,第22行,fileName = input(“ \\ t =>”)TypeError:'str'对象不可调用

# 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=> ")

And here is my main() : 这是我的main():

if __name__ == "__main__":
    input = getInputFile()
    output = getOutputFile()

The problem is when you say input = getInputFile() . 问题是当您说input = getInputFile()

More specifically: 进一步来说:

  1. The program enters the getInputFile() function, and input hasn't been assigned yet. 程序进入getInputFile()函数,但尚未分配input That means the Python interpreter will use the built-in input , as you intended. 这意味着Python解释器将按照您的预期使用内置input
  2. You return filename and get out of getInputFile() . 您返回filename并退出getInputFile() The interpreter now overwrites the name input to be that string. 现在,解释器将input的名称覆盖为该字符串。
  3. getOutputFile() now tries to use input , but it's been replaced with your file name string. getOutputFile()现在尝试使用input ,但是已被您的文件名字符串替换。 You can't call a string, so the interpreter tells you that and throws an error. 您无法调用字符串,因此解释器会告诉您并抛出错误。

Try replacing input = getInputFile() with some other variable, like fileIn = getInputFile() . 尝试用其他变量替换input = getInputFile() ,例如fileIn = getInputFile()

Also, your getOutputFile() is not returning anything, so your output variable will just have None in it. 另外,您的getOutputFile()不返回任何内容,因此您的output变量将只包含None

Depending on what version of python you're using : 根据您使用的python版本

Python 2: Python 2:

var = raw_input("Please enter something: ")
print "you entered", var

Or for Python 3: 或对于Python 3:

var = input("Please enter something: ")
print("You entered: " + var)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM