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

user6003691 picture user6003691 · Jun 4, 2016 · Viewed 7.4k times · Source

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).

So, for example, the list

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

should be written on the text.txt like so

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.

Any ideas please, along with a short explanation of what I am doing wrong will be much appreciated.

Answer

Mureinik picture Mureinik · Jun 4, 2016

If you're writing text, you shouldn't use the "b" mode:

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