Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
On Just One line
#1
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
Reply
#2
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 :)
Reply
#3
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'))))
Reply
#4
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")
Reply
#5
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")
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020