Python Forum
On Just One line - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: On Just One line (/thread-7810.html)



On Just One line - Fumi - Jan-25-2018

Hi there,

Does anyone know how to condense the following into one line as target.write()


target.write (line1)
target.write ("\n")

target.write (line2)
target.write ("\n")

target.write (line3)
target.write ("\n")
Kind Regards


RE: On Just One line - j.crater - Jan-25-2018

Perhaps something like this:
lines = (line1, line2, line3)

target.write("{lines[0]}{newline}{lines[1]}{newline}{lines[2]}{newline}".format(lines=lines, newline="\n"))
Though I am certain there are more elegant and optimal solutions :)


RE: On Just One line - micseydel - Jan-25-2018

A few attempts (not tested)...

Potentially large memory usage
target.write('\n'.join([line1, line2, line3]))
One line, after import
from itertools import chain, repeat
target.writelines(chain(*zip([line1, line2, line3], repeat('\n'))))



RE: On Just One line - Fumi - Jan-31-2018

Well I found a simple way eventually.

target.write(line1);target.write("\n");target.write(line2);target.write("\n");target.write(line3);target.write("\n")



RE: On Just One line - snippsat - Jan-31-2018

Calling write 6 times Doh
A good solution has been posted bye @micseydel.
Working code both do the same:
lst = ['line 1', 'line 2', 'line 3']

# Yes
with open('out_1.txt', 'w') as f_out:
    f_out.write('\n'.join(lst))

# No
with open('out_2.txt', 'w') as target:
    target.write(lst[0]);target.write("\n");target.write(lst[1]);target.write("\n");target.write(lst[2]);target.write("\n")