Last modified: Jan 10, 2023 By Alexander Williams
Python: Various methods to remove the newlines from a text file
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
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.