Python, writing an integer to a '.txt' file

荒凉一梦 提交于 2019-12-04 03:41:56

I think it's simpler doing:

number = 1337

with open('filename.txt', 'w') as f:
  f.write('%d' % number)

But it really depends on your use case.

With python 2, you can also do:

number = 1337

with open('filename.txt', 'w') as f:
  print >>f, number

I personally use this when I don't need formatting.

Write

result = 1

f = open('output1.txt','w')  # w : writing mode  /  r : reading mode  /  a  :  appending mode
f.write('{}'.format(result))
f.close()

Read

f = open('output1.txt', 'r')
input1 = f.readline()
f.close()

print(input1)

The following opens a while and appends the following number to it.

def writeNums(*args):
with open('f.txt','a') as f:
    f.write('\n'.join([str(n) for n in args])+'\n')

writeNums(input("Enter a numer:"))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!