简体   繁体   English

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

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

Having read this question and this question , I am trying to write each element of a list ( mylist ) on a newline on a text file ( text.txt ). 阅读完这个问题这个问题后 ,我试图在文本文件text.txt的换行符上 写一个列表mylist )的每个元素

So, for example, the list 所以,例如,列表

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

should be written on the text.txt like so 应该写在text.txt

a
b
ccc
dd
eeee
f
ggg

I have tried this: 我试过这个:

filename = 'text.txt'

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

which creates the text file but then gives an error; 这会创建文本文件,但会出错; either a TypeError: a bytes-like object is required, not 'str' or io.UnsupportedOperation: write depending on the mode I use. 要么是TypeError: a bytes-like object is required, not 'str'io.UnsupportedOperation: write具体取决于我使用的mode

Any ideas please, along with a short explanation of what I am doing wrong will be much appreciated. 任何想法,以及我做错的简短解释将不胜感激。

If you're writing text, you shouldn't use the "b" mode: 如果您正在撰写文字,则不应使用“b”模式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM