Python Forum
print a line break in writelines() method
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
print a line break in writelines() method
#1
lines=["Line 1","Line 2"]
f=open(r"C:\Users\....\Documents\somefile.txt","w")
f.writelines(lines)
f.close()


How to print a line breaker between items in lines variable (list) when placing them in the text file?
Reply
#2
First: Use a context manager. It closes your file automatically, when the block is left.

with open(r"C:\Users\....\Documents\somefile.txt", "w") as fd:
    for line in lines:
        fd.write(line)
        fd.write("\n")
Doing this with writelines can be done with a trick:
from itertools import repeat, chain


with open(r"C:\Users\....\Documents\somefile.txt", "w") as fd:
    line_sep = repeat("\n")
    line_iter = chain.from_iterable(zip(lines, line_sep))
    fd.writelines(line_iter)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  break print_format lengthy line akbarza 4 273 Mar-13-2024, 08:35 AM
Last Post: akbarza
  problem with spliting line in print akbarza 3 335 Jan-23-2024, 04:11 PM
Last Post: deanhystad
  Print the line before the corrent line tester_V 9 1,488 Nov-18-2022, 08:39 AM
Last Post: Gribouillis
  Performance options for sys.stdout.writelines dgrunwal 11 2,994 Aug-23-2022, 10:32 PM
Last Post: Pedroski55
  Print to a New Line when Appending File DaveG 0 1,189 Mar-30-2022, 04:14 AM
Last Post: DaveG
  writelines only writes one line to file gr3yali3n 2 2,289 Dec-05-2021, 10:02 PM
Last Post: gr3yali3n
  If match not found print last line tester_V 2 2,845 Apr-26-2021, 05:18 AM
Last Post: tester_V
  Print characters in a single line rather than one at a time hhydration 1 1,988 Oct-10-2020, 10:00 PM
Last Post: bowlofred
  How to print string multiple times on new line ace19887 7 5,569 Sep-30-2020, 02:53 PM
Last Post: buran
  Pattern Require Last Line Print() why? Harshil 4 2,373 Aug-08-2020, 04:54 PM
Last Post: Harshil

Forum Jump:

User Panel Messages

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