int
Turn text made of digits, such as "12", into a whole number you can calculate with.
int(text)Deeper Python in the console · In any playground, open Reference to copy these.
Turn text made of digits, such as "12", into a whole number you can calculate with.
int(text)"w" makes the file, or empties it first if it is already there, then writes. with closes the file at the end.
with open("save.txt", "w") as f:
f.write(text)Writes a dictionary or list to a file as JSON text.
import json
with open("game.json", "w") as f:
json.dump(game, f)The first time, there is no file: catch FileNotFoundError instead of stopping.
try:
with open("save.txt") as f:
text = f.read()
except FileNotFoundError:
print("There is no save yet.")Run lines that might fail. If the named error happens, the except lines run instead of the program stopping.
try:
n = int(text)
except ValueError:
print("That is not a number.")Opens the file to read and gives you all of it as one piece of text.
with open("save.txt") as f:
text = f.read()Reads JSON text back into the dictionary or list that was saved.
import json
with open("game.json") as f:
game = json.load(f)