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

6 python list writefile python-3.x

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

因此,例如,列表

mylist = ['a', 'b', 'ccc', 'dd', 'eeee', 'f', 'ggg']
Run Code Online (Sandbox Code Playgroud)

应当在书面text.txt像这样

a
b
ccc
dd
eeee
f
ggg
Run Code Online (Sandbox Code Playgroud)

我试过这个:

filename = 'text.txt'

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

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

任何想法,以及对我做错了什么的简短解释,将不胜感激。

Mur*_*nik 3

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

with open(filename, mode="w") as outfile: 
    # Here ---------------^
Run Code Online (Sandbox Code Playgroud)