在 Python 文本文件的换行符上写入列表的每个元素

Write each element of a list on a newline on a text file in Python

阅读 this question and 后,我正在尝试 将列表的每个元素写在 (mylist) 的换行符上文本文件 (text.txt).

例如,列表

mylist = ['a', 'b', 'ccc', 'dd', 'eeee', 'f', 'ggg']

应该这样写在text.txt

a
b
ccc
dd
eeee
f
ggg

我试过这个:

filename = 'text.txt'

with open(filename, mode="wb") as outfile:  # also, tried mode="rb"
    for s in mylist:
        outfile.write("%s\n" % s)

它创建了文本文件但随后出现错误; TypeError: a bytes-like object is required, not 'str'io.UnsupportedOperation: write 取决于我使用的 mode

如有任何想法,并简要说明我做错了什么,将不胜感激。

如果您正在编写文本,则不应使用 "b" 模式:

with open(filename, mode="w") as outfile: 
    # Here ---------------^