[英]TypeError: 'str' object is not callable (I'm not calling it?)
I'm trying to have a function write to a file with 4 different string variables passed into what is written, but for whatever reason when this is attempted, I get this: 我正在尝试将一个函数写入文件,并将4个不同的字符串变量传递到写入的内容中,但是由于任何原因,尝试这样做时,我都会得到:
Traceback (most recent call last):
File "C:\Python Files\writePy\writePy.py", line 34, in <module>
indent = writeIf(mFile, genCond(), lFile, indent)
File "C:\Python Files\writePy\writePy.py", line 23, in writeIf
file.write('%sif (%s %s %s):' (indentation, cond[0], cond[1], cond[2]))
TypeError: 'str' object is not callable
This is my main code: 这是我的主要代码:
# Main code
lFile = open('OperationLog.txt', mode='w') # Log file for changes
mFile = open('Evolve.txt', mode='w+') # File to be edited
indent = 0 # Indentation for written code
# Write two IF statements with a randomized condition to file, update indentation
indent = writeIf(mFile, genCond(), lFile, indent)
indent = writeIf(mFile, genCond(), lFile, indent)
# Close files
lFile.close()
mFile.close()
and this is the function the error is in: 这是错误所在的函数:
def writeIf(file, cond, log, indent):
indentation = ' ' * (4 * indent) # Number of spaces to add is 4 * indent
file.write('%sif (%s %s %s):' (indentation, cond[0], cond[1], cond[2]))
indent = indent + 1
log.write('Added: IF statement to %s.' % file.name)
return indent
You forgot the modulo operator ( %
): 您忘记了模运算符( %
):
file.write('%sif (%s %s %s):' % (indentation, cond[0], cond[1], cond[2]))
# here --^
在这种情况下使用format()
函数是因为它更合适且易于维护
file.write('{0}if ({1}{2}{3}):'.format(indentation, cond[0], cond[1], cond[2]))
You have to use string formatting: 您必须使用字符串格式:
file.write('%sif (%s %s %s):' % (indentation, cond[0], cond[1], cond[2]))
Without the modulo operator (%), Python interprets it indeed as a function call: 没有模运算符(%),Python确实将其解释为函数调用:
file.write('string'(indentation, cond[0], cond[1], cond[2]))
Though these answers definitely address your problem, you should also be aware of the logging module . 尽管这些答案肯定可以解决您的问题,但您还应该注意日志记录模块 。
import logging
log = logging.getLogger(__name__) #or whatever name you want, like 'my_logger'
log.setLevel(logging.DEBUG)
log.addHandler(logging.FileHandler('OperationLog.txt', mode=w')) #default is 'a'ppend mode
Then your function would look like this: 然后您的函数将如下所示:
def writeIf(file, cond, indent):
indentation = ' ' * (4 * indent) # Number of spaces to add is 4 * indent
file.write('%sif (%s %s %s):' % (indentation, cond[0], cond[1], cond[2]))
indent = indent + 1
log.debug('Added: IF statement to %s.', file.name)
return indent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.