Python闪卡程序报AttributeError: 'str' object has no attribute 'write'求助
报错原因
核心问题是变量名重复覆盖:
在write_flash_cards_to_text_file函数中,你首先通过open("./flash_cards.txt", "w+") as f将打开的文件对象赋值给了变量f,后续遍历闪卡字典的时候又写了for l, f in flash_cards.items(),这一步会把闪卡的定义值(字符串类型)重新赋值给f,覆盖了原本的文件对象。后续调用f.write()时,f已经是字符串,没有write方法,就触发了AttributeError。
而文件被清空是因为w+模式打开文件的第一时间就会清空原有内容,这一步发生在遍历写操作之前,所以哪怕后续代码报错,文件也已经被清空了。
修复方案
- 首先修改
write_flash_cards_to_text_file函数的遍历变量名,避免和文件对象变量冲突:
def write_flash_cards_to_text_file(): """Will line by line write the name and definition for each flash card to a file for saving""" global flash_cards with open("./flash_cards.txt", "w+") as f: # 把遍历变量改成key、value,不要和文件对象f重名 for key, value in flash_cards.items(): f.write(key + "=" + value + "\n")
- 补充
update_flash_cards函数的新增/修改逻辑,当前版本只处理了删除场景,没有把新闪卡写入字典:
def update_flash_cards(key, values, save_to_file=True, delete_flash_card=False): """Will be called whenever adding or deleting or replacing a flash card""" global flash_cards if delete_flash_card: del flash_cards[key] else: # 新增/更新闪卡的逻辑 flash_cards[key] = values if save_to_file: write_flash_cards_to_text_file()
内容的提问来源于stack exchange,提问作者EvaIgoria
相关产品推荐
相关产品推荐

