When you are running a program, the program never actually changes.
What you are searching for is file IO.
You can read and write files to load and save results of your program:
with open('file.txt', 'w') as f: # 'w' to write the file
f.write('useful data')
You can open this file with any text editor and see it contains the text useful data
. To load the file, use read()
with open('file.txt', 'r') as f: # 'r' to read the file
print(f.read()) # prints 'useful data'
Of course it would be useful to write more than one line:
with open('file.txt', 'w') as f: # 'w' to write the file
f.writelines(['more', 'useful', 'data'])
Again, open it in a text editor to check the results.
To read the data, use readlines:
with open('file.txt', 'r') as f: # 'r' to read the file
print(f.readlines()) # prints ['more', 'useful', data']
if you want to save more complex data as you mentioned in a comment you need to use a more complex file format or database. The file formats included in python are: JSON
, CSV
. sqlite
is a database included with python.
Another option is pickle
, but it has many drawbacks and should only be used for temporary storage.
with open("file.json", "w") as f:
json.dump({"complex": ["object"]}, f)
with open("file.json", "r") as f:
x = json.load(f)
with open('file.csv', 'w') as f:
writer = csv.writer(f)
writer.writerows([["fantastic", "table"], ["with many", "entries"]])
with open('file.csv') as f:
reader = csv.reader(f)
for row in reader:
print(row)
For pickle and sqlite I encourage you to read the documentation