首页 > 解决方案 > TypeError: write() 参数必须是 str,而不是 dict (Python)

问题描述

我正在开发一个在 txt 文件中显示我的信息的项目,它与 print 完美配合,但是当我尝试使用 write 时,它​​给了我以下错误:

TypeError: write() 参数必须是 str,而不是 dict

这是我的代码:

for x in range(len(list)):
    outfile = open('message.txt', 'w')
    outfile.write(list[x])
    outfile.close()

标签: python

解决方案


您不能将字典写入字符串。使用print(file=file_object)file.write(str(...))

代码:

for x in range(len(input_list)):
    outfile = open('message.txt', 'w')
    print(input_list[x], file=outfile)
    outfile.close()

推荐阅读