这是代码:
from pathlib import Path
import json
def get_stored_user_info(path):
if path.exists():
contents = path.read_text(path)
user_dict = json.loads(contents)
return user_dict
else:
return None
def get_new_user_info(path):
username = input("username:")
age = input("age:")
city = input("city:")
user_dict = {
'username': username,
'age': age,
'city': city,
}
contents = json.dumps(user_dict)
path.write_text(contents)
return user_dict
def greet_user():
path = Path('user_info.json')
user_dict = get_stored_user_info(path)
if user_dict:
print(f"welcome,{user_dict['username']}")
else:
user_dict = get_new_user_info(path)
print(f"already saved{user_dict['username']}")
greet_user()
第二次运行后的报错:
请问这是什么原因呢
Traceback (most recent call last):
File "/Users/janewang/PycharmProjects/Python_Learning/Chapter 10/remember_me.py", line 38, in <module>
greet_user()
File "/Users/janewang/PycharmProjects/Python_Learning/Chapter 10/remember_me.py", line 30, in greet_user
user_dict = get_stored_user_info(path)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/janewang/PycharmProjects/Python_Learning/Chapter 10/remember_me.py", line 7, in get_stored_user_info
contents = path.read_text(path)
^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/pathlib.py", line 1027, in read_text
with self.open(mode='r', encoding=encoding, errors=errors) as f:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/pathlib.py", line 1013, in open
return io.open(self, mode, buffering, encoding, errors, newline)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: open() argument 'encoding' must be str or None, not PosixPath