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.

Community
  • 1
  • 1

1 Answers1

2

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

with open(filename, mode="w") as outfile: 
    # Here ---------------^
Mureinik
  • 252,575
  • 45
  • 248
  • 283