AbeLinkon AbeLinkon - 1 year ago 137
Python Question

Python - write() versus writelines() and concatenated strings

So I'm learning Python. I am going through the lessons and ran into a problem where I had to condense a great many

into a single
, while having a
between each user input variable(the object of

I came up with:

nl = "\n"
lines = line1, nl, line2, nl, line3, nl

If I try to do:


I get an error. But if I type:

textdoc.write(line1 + "\n" + line2 + ....)

Then it works fine. Why am I unable to use a string for a newline in
but I can use it in

Python 2.7
When I searched google most resources I found were way over my head, I'm still a lay-people.

Answer Source

writelines expects a list of strings, while write expects a single string.

line1 + "\n" + line2 merges those strings together into a single string before passing it to write.

Note that if you have many lines, you may want to use "\n".join(list_of_lines).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download