0

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??

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
charvi
  • 211
  • 1
  • 5
  • 16

4 Answers4

2

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))
Marcin
  • 215,873
  • 14
  • 235
  • 294
2

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

Community
  • 1
  • 1
yossim
  • 306
  • 2
  • 5
1

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

qzzeng
  • 13
  • 3
0

.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)
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76