TypeError: 'str' object is not callable (I

2019-08-04 04:49发布

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:

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

4条回答
Bombasti
2楼-- · 2019-08-04 05:24

You forgot the modulo operator (%):

file.write('%sif (%s %s %s):' % (indentation, cond[0], cond[1], cond[2]))
#                      here --^
查看更多
Rolldiameter
3楼-- · 2019-08-04 05:28

Use the format() function in cases as this as its more suitable and easy to maintain

file.write('{0}if ({1}{2}{3}):'.format(indentation, cond[0], cond[1], cond[2]))
查看更多
Juvenile、少年°
4楼-- · 2019-08-04 05:31

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
查看更多
仙女界的扛把子
5楼-- · 2019-08-04 05:32

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:

file.write('string'(indentation, cond[0], cond[1], cond[2]))
查看更多
登录 后发表回答