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

clickonMe picture clickonMe · Apr 21, 2013 · Viewed 64.4k times · Source

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.

Answer

Alex picture Alex · Apr 21, 2013

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.