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

2019-04-07 18:49发布

Would using the pickle function be the fastest and most robust way to write an integer to a text file?

Here is the syntax I have so far:

import pickle

pickle.dump(obj, file)

If there is a more robust alternative, please feel free to tell me.

My use case is writing an user input:

n=int(input("Enter a number: "))
  • Yes, A human will need to read it and maybe edit it
  • There will be 10 numbers in the file
  • Python may need to read it back later.

4条回答
ら.Afraid
2楼-- · 2019-04-07 19:10

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.

查看更多
戒情不戒烟
3楼-- · 2019-04-07 19:19

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.

查看更多
Evening l夕情丶
4楼-- · 2019-04-07 19:32

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:"))
查看更多
够拽才男人
5楼-- · 2019-04-07 19:35

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)
查看更多
登录 后发表回答