15

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.
clickonMe
  • 521
  • 2
  • 6
  • 12
  • 4
    What's your use case? – jamylak Apr 21 '13 at 12:46
  • Oh, sorry for the lack of detail, but I was using it to write an integer(userinput) into a .txt file. – clickonMe Apr 21 '13 at 12:49
  • 2
    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 Apr 21 '13 at 13:04
  • 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 Apr 21 '13 at 13:12

5 Answers5

19

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.

Alex
  • 1,066
  • 9
  • 13
  • I really can't see a difference in speed. – clickonMe Apr 21 '13 at 12:52
  • 1
    This code has a pretty legacy feel to it. Old-style string formatting is generally to be avoided in new code, and files should be opened using [the `with` statement](http://www.youtube.com/watch?v=lRaKmobSXF4&lc=abvyzpzCoB4yV2md5OqJQZgXTd00VmErxY868GfWsEo&lch=email&feature=em-comment_received&lcor=1). – Gareth Latty Apr 21 '13 at 13:07
  • @Lattyware After much debate I've concluded that old-style string formatting is a stylistic choice, even though `.format` has much greater capabilities, people are still allowed to use it if they wish... `with` should always be used though! Also why use formatting in the first place... `str(number)` – jamylak Apr 21 '13 at 13:13
  • It's not a matter of 'allowed' or not, simply a matter of style, as you originally state, and the docs do recommend avoiding old-style string formatting in new code, which is really the only style advice on the matter. Generally, when working with any code that someone else might end up reading (which I presume of all my code), it's best to follow the conventions outlined by the language in order to increase readability and familiarity. And yes, the better option here is `str(number)` as you say. – Gareth Latty Apr 21 '13 at 13:16
  • @Lattyware As much as I would like that to be the case, It's still generally accepted by the Python community – jamylak Apr 21 '13 at 13:22
5

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)
Dane Lee
  • 131
  • 2
  • 4
1

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:"))
S.B
  • 13,077
  • 10
  • 22
  • 49
HennyH
  • 7,794
  • 2
  • 29
  • 39
1

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.

Benares
  • 1,186
  • 1
  • 7
  • 13
1

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.

Adam
  • 21
  • 4