How do you remove newline from text file in python?

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.

asked Sep 5, 2014 at 10:51

2

add if line.strip[] == '': continue before your print statement.

answered Sep 5, 2014 at 10:59

CurdCurd

11.9k3 gold badges34 silver badges47 bronze badges

0

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]
    

answered Sep 5, 2014 at 11:30

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

answered Sep 5, 2014 at 10:57

James KentJames Kent

5,52323 silver badges48 bronze badges

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.

answered Sep 5, 2014 at 11:01

EtseEtse

1,21515 silver badges27 bronze badges

  • Unknown.PY
  • December 28, 2021

The '\n' character represents the new line in python programming. However, this tutorial will show you various methods to remove the newlines from a text file.

Before starting, let us see the output of our file, which we want to remove all newlines from it.

# Open the file
my_file = open['my_file.txt', 'r']

# Read my_file with newlines character
output = repr[my_file.read[]]

# Output
print[output]

# Close the file
my_file.close[]

Output:

'\nHello World\nHello Python\nHello Javascript\n

Note: I've used the repr[] function to print the file's output with the '\n' character.

Now, let's get started.

Method #1: Remove newlines from a file using replace[]

the replace[] method replaces a specified phrase with another specified phrase. Therefore, we'll use this method to replace the newline character with a non-value.

Syntax

.replace['\n', '']

Example

# Open the file
my_file = open['my_file.txt', 'r']

# File's output
o = my_file.read[]

# Remove all new lines from file
r_newlines = o.replace['\n', '']

# Result
print[r_newlines]

# Close the file
my_file.close[]

Output:

Hello WorldHello PythonHello Javascript

method #2: Remove newlines from a file using splitlines[]

The splitlines[] method splits a string at the newline break and returns the result as a list.

However, we will use the splitlines[] to split the file's output at '\n' and the join[] method to join the result.

Syntax

"".join[file_output.splitlines[]]

Example

# Open the file
my_file = open['my_file.txt', 'r']

# File's output
o = my_file.read[]

# Remove all new lines from the file.
r_newlines = "".join[o.splitlines[]]

# Result
print[r_newlines]

# Close the file
my_file.close[]

Output:

Hello WorldHello PythonHello Javascript

Method #3: Remove newlines from a file using Regex

We can also use the re.sub[] function to remove the newlines from a text file.

Syntax

re.sub['\n', '', output_file]

The sub[] function works like replace[] function.

Example

import re

# Open the File
my_file = open['my_file.txt', 'r']

# File's output
o = my_file.read[]

# Remove all new lines from the file.
r_newlines = re.sub['\n', '', o]

# Result
print[r_newlines]

# Close the file
my_file.close[]

Output:

Hello WorldHello PythonHello Javascript
Advertisements

Conclusion

We've learned different methods to remove the newlines from a text file in this article. Moreover, if you want to remove the newlines from the beginning or end of the text file, you should use strip[] and rstrip[] methods.

How do I get rid of new line in text file?

Click Search..
Click Find and Replace....
Enter \n\s into Find field..
Leave Replace with blank [nothing].
Check Regular expression box..
Click the Find button..

How do you remove end line breaks from lines read from a text file in Python?

Use str. rstrip[] to remove end-line breaks from lines read from a text file.

Does Strip remove newline Python?

Using strip[] method to remove the newline character from a string. The strip[] method will remove both trailing and leading newlines from the string. It also removes any whitespaces on both sides of a string.

Chủ Đề