0

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.

Yann Kull
  • 51
  • 5

5 Answers5

1

Here is an example program that works:

path = "example"
contents = ""

with open(path, "r") as file:
    contents = file.read()

new_contents = contents.replace("\n", "<br>")

with open(path, "w") as file:
    file.write(new_contents)

Your program doesn't work because the replace method does not modify the original string; it returns a new string. Also, you need to write the new string to the file; python won't do it automatically.

Hope this helps :)

P.S. a with statement automatically closes the file stream.

kleinbottle4
  • 151
  • 5
0

Your code reads from the file, saves the contents to a variable and replaces the newlines. But the result is not saved anywhere. And to write the result into a file you must open the file for writing.

with open(path, "r+") as file:
    contents = file.read()

contents = contents.replace("\n", "<br>")

with open(path, "w+") as file:
    contents = file.write(contents)
andole
  • 286
  • 1
  • 7
0

there are some issues in this code snippet.

  1. contents.replace("\n", "<br>") will return a new object which replaced \n with <br>, so you can use html_contents = contents.replace("\n", "<br>") and print(html_contents)
  2. when you use with the file descriptor will close after leave the indented block.
CSJ
  • 2,709
  • 4
  • 24
  • 30
-1

Try this:

import re

with open(path, "r") as f:
    contents = f.read()
    contents = re.sub("\n", "<br>", contents)
    print(contents)
Shan Ali
  • 564
  • 4
  • 12
-1

Borrowed from this post:

import tempfile

def modify_file(filename):

      #Create temporary file read/write
      t = tempfile.NamedTemporaryFile(mode="r+")

      #Open input file read-only
      i = open(filename, 'r')

      #Copy input file to temporary file, modifying as we go
      for line in i:
           t.write(line.rstrip()+"\n")

      i.close() #Close input file

      t.seek(0) #Rewind temporary file to beginning

      o = open(filename, "w")  #Reopen input file writable

      #Overwriting original file with temporary file contents          
      for line in t:
           o.write(line)  

      t.close() #Close temporary file, will cause it to be deleted
Mark Moretto
  • 2,344
  • 2
  • 15
  • 21