Python by writing an integer to a .txt file

Will using pickle be the fastest and most reliable way to write a whole to a text file?

Here is the syntax that I still have:

import pickle pickle.dump(obj, file) 

If there is a more reliable alternative, please let me know.

My use case records user input:

 n=int(input("Enter a number: ")) 
  • Yes, a person will need to read it and possibly edit it
  • There will be 10 numbers in the file.
  • Python may need to be read later.
+6
source share
4 answers

I think this is easier:

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

But it really depends on your use case.

+7
source

Using python 2 you can also:

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

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

+1
source

To 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) 
0
source

Then the message opens and adds the next 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:")) 
-1
source

All Articles