How to replace line feeds in a text file with Python

The below Python code will replace line feeds in a text file with space or replace consecutive line feeds with one line feed. I named this replacelf.py.

# file outtext in the current directory
file_path = r"./outtext"

# Note that the file has to be opened in binary mode.
with open(file_path, "rb") as open_file:
    #read contents of file into a variable
	content = open_file.read()

# Replace the bytes
#replace two line feeds with a ~
content = content.replace(b'\n\n', b'~')
#replace one line feed with a space.
content = content.replace(b'\n', b' ')
#replace the ~ to two line feeds
content = content.replace(b'~', b'\n\n')

# Write the bytes to the file
with open(file_path, "wb") as open_file:
	open_file.write(content)

To run this code, open a terminal window, change to the path where replacelf.py is store and simply type:

$ python3 replacelf.py <enter>

Leave a comment