Skip to content Skip to sidebar Skip to footer

Python, Writing An Integer To A '.txt' File

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 t

Solution 1:

I think it's simpler doing:

number = 1337withopen('filename.txt', 'w') asf:
  f.write('%d' % number)

But it really depends on your use case.

Solution 2:

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)

Solution 3:

With python 2, you can also do:

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

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

Solution 4:

The following opens a while and appends the following number to it.

defwriteNums(*args):
withopen('f.txt','a') as f:
    f.write('\n'.join([str(n) for n in args])+'\n')

writeNums(input("Enter a numer:"))

Solution 5:

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.

Post a Comment for "Python, Writing An Integer To A '.txt' File"