Jane_Python学习ing 2024-01-17 04:28 采纳率: 66.7%
浏览 9
已结题

TypeError: open() argument 'encoding' must be str or None, not PosixPath

这是代码:

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

  • 写回答

2条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2024-01-17 06:01
    关注

    【以下回答由 GPT 生成】

    这个问题是由于在调用path.read_text()方法时,传入了错误的参数类型导致的。具体来说,在get_stored_user_info()函数中的以下代码有问题:

    contents = path.read_text(path)
    

    read_text()方法不需要传入文件路径作为参数,它会自动使用当前的Path对象进行文件读取。因此,正确的代码应该是:

    contents = path.read_text()
    

    修改后的get_stored_user_info()函数的代码如下:

    def get_stored_user_info(path):
        if path.exists():
            contents = path.read_text()
            user_dict = json.loads(contents)
            return user_dict
        else:
            return None
    

    接下来,通过运行修改后的代码来验证修改是否成功。

    最终,完整的代码如下:

    from pathlib import Path
    import json
    
    def get_stored_user_info(path):
        if path.exists():
            contents = path.read_text()
            user_dict = json.loads(contents)
            return user_dict
        else:
            return None
    
    def get_new_user_info(path):
        username = input("请输入用户名:")
        age = input("请输入年龄:")
        city = input("请输入城市:")
        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"欢迎回来,{user_dict['username']}!")
        else:
            user_dict = get_new_user_info(path)
            print(f"欢迎初次见面,{user_dict['username']}!")
    
    greet_user()
    

    通过以上修改,应该能够解决报错的问题。如果还有其他问题,请及时反馈。


    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 1月17日
  • 已采纳回答 1月17日
  • 创建了问题 1月17日

悬赏问题

  • ¥30 要求把带有文件的上级文件夹改成文件的名字。要求BAT
  • ¥30 不会,学习,有偿解答
  • ¥15 SQL查询语句报错(检查)
  • ¥15 此表中公式应该怎么写
  • ¥15 求HI-TECH PICC 9.50 PL3安装包
  • ¥15 下载ctorch报错,求解
  • ¥15 如何入门学习c语言,单片机
  • ¥15 idea 编辑语言的选择
  • ¥15 Windows下部署Asmjit
  • ¥15 请问双层规划模型的上下层目标函数不一致,是如何保证迭代收敛性的