10
votes

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.
5
What's your use case? - jamylak
Oh, sorry for the lack of detail, but I was using it to write an integer(userinput) into a .txt file. - clickonMe
Your question is still unclear. How will the file be used? If your program needs to read the file later and retrieve the number, pickle might be appropriate. Otherwise, it probably is not. - Adam
The main questions are: Is there any possibility a human will need to read this file? edit it? a non-python program might want to read it? edit it? How much data will be in the file? Will it just be one number? Many numbers? - Gareth Latty

5 Answers

13
votes

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
votes

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)
1
votes

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.

0
votes

I just encountered a similar problem. I used a simple approach, saving the integer in a variable, and writing the variable to the file as a string. If you need to add more variables you can always use "a+" instead of "w" to append instead of write.

f = open("sample.txt", "w")
integer = 10
f.write(str(integer))
f.close()

Later you can use float to read the file and you wont throw and error.

-1
votes

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:"))