python - Type Error when running function -
i'm trying use fileinput replace line in file, if word in line. appends file. runs gives me typeerror, i'm trying figure out error is.
tagname = 'somestring' def add_tags(): line in fileinput.fileinput('/tmp/hosttags.mk',inplace=1): if 'end_tags' in line: line = line.replace(""" ('end_tags',""", """('%s', u'/%s', [('%s', u'%s tag', [])]), ('end_tags', u'testing/end_tags_start', [('end_tag_id', u'end_tag_description', [])])]""") % ( tagname, tagname, tagname, tagname) print line.strip() error:
traceback (most recent call last): file "./tag_update.py", line 57, in <module> checkmk_srv_tag_update() file "./tag_update.py", line 54, in checkmk_srv_tag_update add_tags() file "./tag_update.py", line 45, in add_tags [('end_tag_id', u'end_tag_description', [])])]""") % ( tagname, tagname, tagname, tagname) typeerror: not arguments converted during string formatting end result of file being updated:
('house', u'/house', [('house', u'house tag', [])]), ('somestring', u'/somestring', [('somestring', u'somestring tag', [])]), ('end_tags', u'testing/end_tags_start', [('end_tag_id', u'end_tag_description', [])])] thanks
you have wrongly put bracket, doing
line = line.replace("xxx", "%s %s") % (tagname, tagname) where suppose be
line = line.replace("xxx", "%s %s" % (tagname, tagname) ) lets line = 'xxx', replace text match, works because 1st replace become "%s %s" % (tagname, tagname)
when replace text not match, fail because become original line 'xxx' % (tagname, tagname) ,thus error
the error can fix changing if part into
if " ('end_tags'," in line: - fix wrong bracket
- as luke woodward mention, if checking not matching replace text portion, can remove if part, code work replace not happen when replace text not matching
- instead of %, suggest use string format
line = line.replace("xxx", "{0} {0}".format(tagname) )
Comments
Post a Comment