import os
def save_progress(progress, filename='progress.txt'):
"""保存当前进度到文件"""
with open(filename, 'w') as f:
f.write(str(progress))
def load_progress(filename='progress.txt'):
"""从文件加载上次的进度,如果文件不存在,则创建文件并返回 0"""
if os.path.exists(filename):
with open(filename, 'r') as f:
return int(f.read())
else:
# 如果文件不存在,创建文件并写入 0
with open(filename, 'w') as f:
f.write('0')
return 0
def calculate_sum(start, end):
"""计算从 start 到 end 的总和,并每 100 次保存一次进度"""
total = 0
for i in range(start, end + 1):
total += i
if (i - start + 1) % 1000000 == 0: # 每 100 次保存进度
save_progress(i, 'progress.txt')
return total
def main():
"""主程序"""
start = load_progress('progress.txt')
end = 99999999999999999999999999999999999
if start == 0:
print("Starting the calculation from the beginning.")
else:
print(f"Resuming the calculation from {start + 1}.")
# 计算从当前进度到结束的部分
result = calculate_sum(start + 1, end)
# 最后保存进度
save_progress(end, 'progress.txt')
print(f'Total sum from {start + 1} to {end} is {result}')
if __name__ == '__main__':
main()
python保存程序数据状态到文件,下次运行恢复上次运行位置
最新推荐文章于 2024-11-10 08:15:38 发布