Reputation: 933
Trying to write
to a file with variables, but that is returning error:
template = """1st header line
second header line
There are people in rooms
and the %s
"""
with open('test','w') as myfile:
myfile.write(template.format()) % (variable)
Upvotes: 1
Views: 6013
Reputation: 52071
myfile.write(template.format())
returns nothing to which you are using %
operator to concatenate
You can perfectly use %s
.The problem is you mismatched parenthesis and the parenthesis i.e. )
should be after your variable as in myfile.write(template.format() % (variable))
. But as template.format()
is redundant, it can be ignored. Thus the correct way is
myfile.write(template % (variable))
Note:- Any string with an empty format()
and no {}
in the string returns the string itself
Upvotes: 1
Reputation: 368914
The given string literal is printf-style string. Use str % arg
:
with open('test', 'w') as myfile:
myfile.write(template % variable)
To use str.format
, you should use placeholder {}
or {0}
instead of %s
.
Upvotes: 1
Reputation: 643
The .format
method expects you to template the blanks to be filled in your string with the {}
-style, not %s
. It also expects the interpolated values to be given as its arguments.
template = """1st header line
second header line
There are people in rooms
and the {}
"""
myfile.write(template.format(variable))
Upvotes: 2