1

我试图让一个函数写入一个文件,其中有 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

这是我的主要代码:

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

这是错误所在的函数:

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
4

4 回答 4

9

您忘记了模运算符 ( %):

file.write('%sif (%s %s %s):' % (indentation, cond[0], cond[1], cond[2]))
#                      here --^
于 2013-10-15T13:35:33.570 回答
5

在 case 中使用该format()功能,因为它更合适且易于维护

file.write('{0}if ({1}{2}{3}):'.format(indentation, cond[0], cond[1], cond[2]))
于 2013-10-15T13:41:12.007 回答
4

您必须使用字符串格式:

file.write('%sif (%s %s %s):' % (indentation, cond[0], cond[1], cond[2]))

如果没有模运算符 (%),Python 确实将其解释为函数调用:

file.write('string'(indentation, cond[0], cond[1], cond[2]))
于 2013-10-15T13:35:54.063 回答
3

虽然这些答案肯定能解决您的问题,但您也应该了解logging 模块

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

然后你的函数看起来像这样:

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
于 2013-10-15T13:46:23.540 回答