In this post we will be creating a Python script that will read from an existing text file and remove any new lines that may exist. To do this we will be using the ‘replace()’ function which finds and replaces a given character or phrase with another.
See the snippet of Python code below which reads the text file and then replaces any instances of a new line with a single white space instead.
with open('File.txt', 'r') as file:
text = file.read().replace('\n', ' ')
print(text)
And so if your text file were to contain the following text. For example the word ‘Hello’ followed by ‘World!’ on the next line.
Hello
World!
The script would return the below as output, combining the two words together on to the same line.
Hello World!
>>>
Take a look at some of our other content around the Python programming language by clicking here.