存储
import json
from pathlib import Path
number = input("please input the number you like\n")
path = Path("number.json")
contents = json.dumps(number)
path.write_text(contents)
读取
import json
from pathlib import Path
path = Path("number.json")
contents = path.read_text()
number = json.loads(contents)
print(f"I know you favorite number! It’s {number}")
结合
import json
from pathlib import Path
number = input("please input the number you like")
path = Path("number.json")
contents = json.dumps(number)
path.write_text(contents)
def write_number(path):
"""提示用户输入喜欢的数字"""
number = input("please input the number you like")
contents = json.dumps(contents)
path.write_text(contents)
return number
def read_contents(path):
"""读取文件是否内存储的数值"""
if path.exists():
contents = path.read_text()
number = json.loads(contents)
return number
else:
return None
def print_contents():
"""打印用户喜欢的数字"""
path = Path("number.json")
number = read_contents(path)
if number:
print(f"I know you favorite number! It's {number}")
else:
number = write_number(path)
print_contents()