1

New to programming and have just written my first program in Python. The program works well in the initial steps but whatt I'm not sure about is how to store values so the next time the programm is ran it starts with those values. Here is the code in case I'm not making sense:

monthly_wage = int(input("How much were you paid this month? "))

monthly_days = int(input("How many days this month? "))

saved = 0

while (monthly_days > 0):
    daily_max = round(monthly_wage/monthly_days)
    daily_spend = int(input("How much have you spent today? "))
    daily_remain = round(daily_max - daily_spend, 2)
    saved = saved + daily_remain
    monthly_wage = monthly_wage - daily_spend
    monthly_days -- 1
    print("Your remaining wage is: £", monthly_wage)
    print("You can spend a total of £", daily_max, " each day")
    print("You have saved £", saved, " so far this month")
    print("There are ", monthly_days, " days remaining")

So what i want is the next time I run the programme instead of running through the initial steps it would start at requesting the daily spend. I'm assuming I will need to store the values in a file and rewrite the program to take the values from that file but i'm not having much luck when searching how this is done. Hopefully someone can point me in the right direction for this.

Thanks.

BJLX
  • 11
  • 2
  • Yup save the values in a file. Check out [this](https://stackoverflow.com/questions/6568007/how-do-i-save-and-restore-multiple-variables-in-python) SO question. – Captain Jack Sparrow Apr 19 '20 at 21:33

2 Answers2

0

There are multiple ways to persist data in a python program. You can write to a text file or using the pickle module.

import pickle

list_of_values = [10, 55, 777] # the values you want to persist
my_file = open(r'C:\data.pkl', 'wb')
pickle.dump(list_of_values, my_file)
my_file.close()

# reload your data
load_file= open(r'C:\data.pkl', 'rb')
load_data = pickle.load(load_file)
load_file.close()
Sam
  • 86
  • 2
  • 10
0

This is by no means the best practice, but it's the simplest way

from pathlib import Path
file = Path("filename")
if file.exists():
    content = file.open("r").read()

# update content somehow
file.open("w").write(content)

You should look into opening files with the with statement, but lets make sure you get this snippet working first.

Uri Goren
  • 13,386
  • 6
  • 58
  • 110