【问题标题】:Is it possible to save an integer to use again? [duplicate]是否可以保存一个整数以再次使用? [复制]
【发布时间】:2018-10-30 11:18:30
【问题描述】:

我刚开始学习 Python,遇到了一个问题,我想保存一个整数,以便在程序关闭时再次使用。我一直在四处寻找,但找不到任何关于它的信息。目前我写的代码:

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

我尝试将Num 保存到另一个文件中,然后用它来保存它。但是,它保存为字符串而不是int,所以我尝试使用int(),但仍然没有帮助。

提前感谢您的帮助。

【问题讨论】:

  • _所以我尝试使用 int() 仍然没有帮助 - 出了什么问题?如果我open('save.txt','w').write(str(some_int)),那么int(open('save.txt').read()) 应该可以工作。

标签: python persistence


【解决方案1】:

使用 pickle 库。

import pickle
num = 4
pickle.dump(num, "num_file.txt")
loaded_num = pickle.load("num_file.txt")

【讨论】:

  • 文件扩展名不必是.txt
  • 我一直以为约定是.pkl!
  • 我认为 :) 我有时在 windows 上使用 txt 来查看里面的内容...
【解决方案2】:

您可以使用 JSON,然后无论是 Python 还是其他可以读取并使用您的部分结果(不限于 int)运行的语言都没有关系。下面是一个程序示例,该程序(低效)计算几个素数并在每次运行时从中断处继续:

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)

【讨论】:

    猜你喜欢
    • 2020-03-20
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    • 2014-06-16
    • 2015-12-23
    相关资源
    最近更新 更多