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

1

6

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.

Policewoman answered 4/6, 2016 at 11:14 Comment(0)
V
3

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

with open(filename, mode="w") as outfile: 
    # Here ---------------^
Vulgarian answered 4/6, 2016 at 11:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.