AttributeError: ‘str’ 对象没有属性 ‘read’

AttributeError: ‘str’ 对象没有属性 ‘read’

AttributeError: ‘str’ object has no attribute ‘read’

Python“AttributeError: ‘str’ object has no attribute ‘read’” 发生在我们read()在字符串(例如文件名)而不是文件对象上调用该方法或json.load()错误使用该方法时。要解决该错误,请
read()在打开文件后调用文件对象上的方法。

attributeerror str 对象没有属性读取

下面是错误如何发生的示例。

主程序
file_name = 'example.txt' with open(file_name, encoding='utf-8') as f: # ⛔️ AttributeError: 'str' object has no attribute 'read' read_data = file_name.read() print(read_data)

我们试图read()在文件名字符串而不是导致错误的文件对象上调用该方法。

如果您正在从文件中读取,请确保改为调用read()文件对象上的方法。

主程序
file_name = 'example.txt' with open(file_name, encoding='utf-8') as f: # ✅ calling read() on file object read_data = f.read() print(read_data)

错误的另一个常见原因是json.load()在尝试将 JSON 字符串解析为本机 Python 对象时使用该方法。

主程序
import json # ⛔️ AttributeError: 'str' object has no attribute 'read' result = json.load('{"name": "Alice"}')

json.load方法用于将文件反序列化为 Python 对象,而
json.loads方法用于将 JSON 字符串反序列化为 Python 对象。

如果您尝试将 JSON 字符串解析为本机 Python 对象,请改用
json.loads(with s) 方法。

主程序
import json result = json.loads('{"name": "Alice"}') print(type(result)) # 👉️ <class 'dict'> print(result) # 👉️ {'name': 'Alice'}

json.loads()我们使用该方法将 JSON 字符串解析为字典。

如果您尝试使用该json.load()方法将文件反序列化为 Python 对象,请打开文件并将文件对象传递给该json.load()
方法。

主程序
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_data = json.load(f) print(my_data) # 👉️ {'name': 'Alice', 'age': 30}

json.load()方法需要一个包含实现.read()方法的 JSON 文档的文本文件或二进制文件。如果您json.load()
使用字符串调用该方法,它会尝试调用该
read()字符串上的方法。

如果您在使用模块时遇到错误,请在调用方法urllib之前打开请求。read()

主程序
import urllib.request with urllib.request.urlopen('http://www.python.org/') as f: # 👇️ call read() here print(f.read())

开始调试的一个好方法是print(dir(your_object))查看字符串具有哪些属性。

这是打印 a 的属性的示例string

主程序
my_string = 'hello world' # [ 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', # 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', # 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', # 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', # 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', # 'title', 'translate', 'upper', 'zfill'] print(dir(my_string))

如果将一个类传递给
dir()函数,它会返回该类属性的名称列表,并递归地返回其基类的属性。

If you try to access any attribute that is not in this list, you would get the “AttributeError: str object has no attribute error”.

Since the str object doesn’t implement a read() method, the error is caused.

Conclusion #

The Python “AttributeError: ‘str’ object has no attribute ‘read'” occurs when
we call the read() method on a string (e.g. a filename) instead of a file
object or use the json.load() method by mistake. To solve the error, call the
read() method on the file object after opening the file.