Kunal Telangi
Kunal Telangi

Reputation: 15

Data file handling

In this program how should I store the the output of a=1+1 in txt file? But write() argument must be str, not int

a = 1+1
w = open('r.txt','w')
w.write(a)

Upvotes: 0

Views: 101

Answers (4)

Ramsey
Ramsey

Reputation: 111

I run the code.Its shows.

Traceback (most recent call last):
File "D:/projects/test_celery/test.py", line 3, in <module>
  w.write(a)
TypeError: write() argument must be str, not int

Process finished with exit code 1

Obviously,you should trans the int byte to str,then you can write into a txt file.

a = 1 + 1
with open('r.txt', 'w') as w:
   w.write(str(a))

By the way,remember always to w.close() before exiting and 'with open() as w' can do the job.

Upvotes: 0

adamkwm
adamkwm

Reputation: 1173

You may try to use print() with file argument, but of course using file.write() is more readable.

with open("r.txt", "w") as w:
    print(1 + 1, file=w)

Upvotes: 1

user15801675
user15801675

Reputation:

You can simply convert the sum to a string using the built-in str function.

a = 1+1
w = open('r.txt','w')
w.write(str(a))

References

Also, it is better to open files with the with open.... because the file is guaranteed to close when the with block ends.

a = 1+1
with open('r.txt','a') as w:
    w.write(str(a))

Upvotes: 3

U13-Forward
U13-Forward

Reputation: 71610

You have to use str.

You could also try with with open:

a = 1 + 1
with open('r.txt', 'w') as w:
    w.write(str(a))

Upvotes: 0

Related Questions