2

If I want to remove line breaks from a text file such as this:

hello

there

and I use a simple code like this:

with open('words.txt') as text:
  for line in text:
    print (line.strip())

It outputs this:

hello

there

However, I want my code to output this:

hello
there

How can I do this? Thanks in advance.

Hjekien
  • 89
  • 2
  • 2
  • 4

4 Answers4

3

add if line.strip() == '': continue before your print statement.

Curd
  • 12,169
  • 3
  • 35
  • 49
3

I see two ways to achieve what you want.

  1. Reading line by line

    with open('bla.txt') as stream:
        for line in stream:
            # Empty lines will be ignored
            if line.strip():
                print(line)
    
  2. Reading all contents

    import re
    with open('bla.txt') as stream:
        contents = stream.read()
        print re.sub('\s$', '', contents, flags=re.MULTILINE)
    
Fabio Menegazzo
  • 1,191
  • 8
  • 9
0

if its only linebreaks you want to remove, you could use string.replace("\n", "")

or if it only uses carraige returns instead of newlines (*nix) then string.replace("\r", "")

James

James Kent
  • 5,763
  • 26
  • 50
0

You need to test if a line is empty or not to solve this.

with open('words.txt') as text:
    for line in text:
        if line:
            print (line.strip())

In python empty-strings are falsy. That is, an if-test on an empty string will be considered false.

Etse
  • 1,235
  • 1
  • 15
  • 28