How do I use a write()
in Python to write a statement like "value of a is:",a
?
We use
print "value of a is:",a
but
f.write("value of a is:",a)
gives an error. How do I write it into a file??
How do I use a write()
in Python to write a statement like "value of a is:",a
?
We use
print "value of a is:",a
but
f.write("value of a is:",a)
gives an error. How do I write it into a file??
I guess this is what you are after:
with open('somefile.txt', 'w') as the_file:
the_file.write("value of a is: {}\n".format(a))
If a is an integer:
f.write("value of a is: %d" % (a))
If you're looking for a more robust solution, see: Python string formatting: % vs. .format
I guess your are look at for these codes:
a=10
f=open("test.dat","w")
f.write('valiue is a is:'+str(a))
f.close()
Because f.write() expected a character buffer object, you have to convert a in to string to write to your file
.write()
takes a complete string, not one of the following format:
"value of a is:",a
Instead of calling f.write("value of a is:",a)
, assign "value of a is:",a
to a variable first:
string = "value of a is:", a
f.write(string)