pythonpython-3.xfile-manipulation

How to make a program that replaces newlines in python file with a string


I am trying to display my python file in html and therefore I would like to replace every time the file jumps to a newline with < br> but the program I've written is not working.

I've looked on here and tried changing the code around a bit I have gotten different results but not the ones I need.


with open(path, "r+") as file:
    contents = file.read()
contents.replace("\n", "<br>")
print(contents)
file.close()

I want to have the file display < br> every time I have a new line but instead the code dosen't change anything to the file.


Solution

  • Try this:

    import re
    
    with open(path, "r") as f:
        contents = f.read()
        contents = re.sub("\n", "<br>", contents)
        print(contents)