Skip to content Skip to sidebar Skip to footer

How To Write Data To A File In Hindi Language?

I am trying to write data to a file in a non-roman script using python tkinter. I want to write data to a file in Hindi language which follows the Devanagari Script. While, it is w

Solution 1:

Tried this code and it worked just fine with Python 3.6.5 under Windows 10:

text = """<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head><body>
<p>एक  दो</p>
</body></html>"""withopen('test.html', 'w', encoding='utf8') as file:
    file.write(text)

What is your environment? Have you tried to open the file in different editors and/or browsers?

Solution 2:

According to the File Dialogs documentation for asksaveasfilename, there is no encding option available. But you can open the file in write mode, specify the encoding as 'utf-8', and write to it later.

import tkinter as tk
from tkinter import filedialog

def Test():        
    root = tk.Tk()

    myFile = filedialog.asksaveasfilename(defaultextension='.html')

    ifnot myFile:
        returnwithopen(myFile, 'w', encoding='utf-8') as f:
        f.write("एक" + "<br>\n"+ "दो" + "<br>\n")   

    root.mainloop()


Test()

Solution 3:

I found a very feasible solution to the problem I was facing earlier. So, I am answering my own question as it might turn out handy for anyone who runs into an error similar to mine. The solution shall work for writing to a file in any language that is in a non-roman script (Hindi,Urdu, Chinese, Russian, Arabic etc). The programming environment I am working in is python 3.6.

The only rectifications to the code are-

  1. Change mode='w' to mode='wb', so that the data to be written in file is read in bytes since for any form of encoding, the interpreter must scan the data in bytes.
  2. In the (.write) command line, add encoding in the form of .encode('utf-8'). As, I mentioned in my problem, encode='utf-8' is not an 'attribute' of (filedialog.asksaveasfile). However, it is actually a 'method' and is it be to formulated that way only. So, the new rectified code is-

     def save_file_hindi(event=""):
     data = filedialog.asksaveasfile(mode="wb", defaultextension=".html")
     ifdatais None:
         returndata.write(("एक" + "<br>\n"+ "दो" + "<br>\n").encode('utf-8'))
     data.close()
    

Post a Comment for "How To Write Data To A File In Hindi Language?"