1

I've just started learning Python and I'm running into a problem where I want to save an integer to use again if the program is shutdown. I've been looking around, but can't find anything about it. The code I've written so far:

from __future__ import print_function
collatz = open("collatz.txt", "w+")
Num = 5
calcNum = Num
while Num>0:
    if calcNum % 2 == 0:
       calcNum /= 2
       print(calcNum, file = collatz)
    else:
        calcNum = (calcNum*3)+1
        print(calcNum, file = collatz)
    if calcNum == 4:
        print("The infinite loop has been reached, moving on to the next number.", file = collatz)
        Num += 1
        print(Num, file = collatz)
        calcNum = Num

I tried to save Num into another file and then use that to keep it. However, it saves as a string instead of an int, so I tried to use int() which still didn't help.

Thanks in advance for any help.

cdlane
  • 40,441
  • 5
  • 32
  • 81
Albin Jonsson
  • 21
  • 2
  • 6
  • _so I tried to use int() which still didn't help- what went wrong? If I `open('save.txt','w').write(str(some_int))`, then `int(open('save.txt').read())` should work. – tdelaney May 20 '18 at 18:31

2 Answers2

3

Use the pickle library.

import pickle
num = 4
pickle.dump(num, "num_file.txt")
loaded_num = pickle.load("num_file.txt")
Hadus
  • 1,551
  • 11
  • 22
1

You can use JSON and then it doesn't matter if it's Python or some other language that reads in and runs with your partial result (not limited to int). Here's an example of a program that (inefficiently) computes a few primes and picks up where it left off each time it's run:

import json
from math import factorial
from os.path import isfile

FILE_NAME = "number.json"

def is_prime(x):  # not efficient, but short (by @aikramer2)
    return factorial(x - 1) % x == x - 1

if isfile(FILE_NAME):
    with open(FILE_NAME) as handle:
        number = json.load(handle)
else:
    number = 2  # no seed, begin anew
    print(number)

for number in range(number + 1, number + 10):
    if is_prime(number):
        print(number)

with open(FILE_NAME, "w") as handle:
    json.dump(number, handle)
cdlane
  • 40,441
  • 5
  • 32
  • 81