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
  • 107,083
  • 22
  • 201
  • 376
charvi
  • 201
  • 5
  • 14

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
  • 168,023
  • 10
  • 140
  • 197
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
  • 256
  • 1
  • 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
  • 18,339
  • 6
  • 41
  • 73