Home > Back-end >  How to display text from a .txt file with proper line breaks when output to terminal
How to display text from a .txt file with proper line breaks when output to terminal

Time:11-13

I am writing a relatively basic typing test script to be run in the terminal. I have an example text block which is saved as text_block.txt:

Roads go ever ever on,
Over rock and under tree,
By caves where never sun has shone,
By streams that never find the sea;
Over snow by winter sown,
And through the merry flowers of June,
Over grass and over stone,
And under mountains in the moon.

and the following function to read this in:

def load_text():
    with open("text_block.txt", "r") as f:
        lines = []
        for line in f:
            lines.append(line.strip())
        lines = ''.join(lines)
        return lines

which gives the following when displayed in the terminal:

Roads go ever ever on,Over rock and under tree,By caves where never sun has shone,By streams that never find the sea;Over snow by winter sown,And through the merry flowers of June,Over grass and over stone,And under mountains in the moon.

How do I get this to have proper line breaks to mimic the formatting of the text file?

CodePudding user response:

You can get your desired output by inserting line breaks between all the words:

a = ["abc", "deg", "II"]
b = "\n".join(a)
>>> b
'abc\ndef\nII'
>>> print(b)
abc
deg
II

However you might want to add a line break at the end, in which case just add:

b  = "\n"
>>> print(b)
abc
deg
II

But you can also improve your code. You can use list comprehension to get rid of some extra lines (it does the same as your example).

with open() as f:
    return "".join([for line in f])

Removing .strip() will keep everything from the file (including existing line breaks).

Or shorter:

with open() as f:
    return "".join(f.readlines())
  • Related