1

I am working in python tkinter and I am trying to write a code for writing some contents to a file and saving it. I have used filedialog to do so. I wish to write the contents in every next line. While there are so errors in running the code, even after writing "\n", it is not writing to the next line. The "\n" just adds a space after. How to resolve this issue?

I have tried using the "\n" keyword in different ways possible. Yet, it is not writing to the next line. Instead it only adds a space after, just like &nbsp does.

Following is the relevant part of the code:

def save_file(event=""):
    data = filedialog.asksaveasfile(mode="w", defaultextension=".html")
    if data is None:
        return

    data.write("Content-1" + "\n"+ "Content-2" + "\n")
    data.close()

I expect the data to be written in the file as:

Content-1

Content-2

But it is writing to the file as: Content-1 Content-2

Pratyush Karna
  • 179
  • 1
  • 2
  • 10

1 Answers1

1

You are creating html - files. \n it it are meaningless if you look at your file using a browser (which is the go-to for html-files).

You need to write html-linebreaks to you file if you want it to break using a browser when displaying the interpreted html.

data.write("Content-1" + "<br>\n"+ "Content-2" + "<br>\n")

That way you can "see" htlm newlines in your browser.

Edit your file in a Textfile-editor -not a browser- to see the \n that are actually written to your file.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Thank you so much for the help. It is working fine. I also have another small doubt, it would be of great help if you can clear that as well. I want to write contents to the .html file in a different non-roman script. Like, I am trying to write it in Hindi language which is a Devanagari script, but it doesn't display anything. How to resolve this issue? I tried doing : data = filedialog.asksaveasfile(mode="w", defaultextension=".html", encoding='utf-8') – Pratyush Karna Apr 01 '19 at 15:41
  • @prat Not sure I can. If it is unrelated, ask a new question and SO will take care of it. – Patrick Artner Apr 01 '19 at 15:42
  • I have added a detailed question. Please go through this- https://stackoverflow.com/questions/55459768/how-to-write-data-to-a-file-in-hindi-language?noredirect=1#comment97632279_55459768 – Pratyush Karna Apr 01 '19 at 16:42