AttributeError: ‘str’ 对象没有属性 ‘write’
AttributeError: ‘str’ object has no attribute ‘write’
Python“AttributeError: ‘str’ object has no attribute ‘write’” 发生在我们write()
对字符串(例如文件名)而不是文件对象调用方法时。要解决该错误,请write()
在打开文件后调用文件对象上的方法。
下面是错误如何发生的示例。
file_name = 'example.txt' with open(file_name, 'w', encoding='utf-8') as my_file: # ⛔️ AttributeError: 'str' object has no attribute 'write' file_name.write('first line' + '\n') file_name.write('second line' + '\n') file_name.write('third line' + '\n')
问题是我们write()
在文件名上调用了方法,它是一个字符串。
相反,write()
在打开文件对象后调用该方法。
file_name = 'example.txt' with open(file_name, 'w', encoding='utf-8') as my_file: # ✅ calling write() on file object my_file.write('first line' + '\n') my_file.write('second line' + '\n') my_file.write('third line' + '\n')
with open()
即使抛出异常,语法也会自动关闭文件。
或者,您可以将文件对象存储到变量中并手动关闭它。
file_name = 'example.txt' my_file = open(file_name, 'w', encoding='utf-8') my_file.write('first line' + '\n') my_file.write('second line' + '\n') my_file.write('third line' + '\n') my_file.close()
请注意,最好使用with open()
语法,因为它会在我们完成后自动关闭文件。
如果需要将数据附加到文件,请使用a
标志而不是w
.
file_name = 'example.txt' with open(file_name, 'a', encoding='utf-8') as my_file: my_file.write('first line' + '\n') my_file.write('second line' + '\n') my_file.write('third line' + '\n')
如果您需要从文件读取和写入文件,请使用该r+
标志。
file_name = 'example.txt' with open(file_name, 'r+', encoding='utf-8') as my_file: read_data = my_file.read() print(read_data) my_file.write('first line' + '\n') my_file.write('second line' + '\n') my_file.write('third line' + '\n')
开始调试的一个好方法是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))
If you pass a class to the
dir() function, it
returns a list of names of the class’s attributes, and recursively of the
attributes of its bases.
Since the str
object doesn’t implement a write()
method, the error is
caused.
Conclusion #
The Python “AttributeError: ‘str’ object has no attribute ‘write'” occurs when
we call the write()
method on a string (e.g. the filename) instead of a file
object. To solve the error, call the write()
method on the file object after
opening the file.