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

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

所以,例如,列表

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:需要类似字节的对象,而不是’str’或io.UnsupportedOperation:写,具体取决于我使用的模式.

任何想法,以及我做错的简短解释将不胜感激.

最佳答案 如果您正在撰写文字,则不应使用“b”模式:

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