0

When I usually open files I use open syntax where it gives me option of opening with a specific encoding, for eg.

f = open('L2G8970_PSA_PVS_SmokeTest_Report_Trial.xml', encoding="utf8")

But when I am trying with tkinter's filedialog.askopenfile() syntax

filename = filedialog.askopenfilename()

file is getting opened with different encoding.

Please help on how to import with utf-8 encoding.

Siddharth Dushantha
  • 1,391
  • 11
  • 28
  • 1
    You probably shouldn't be using `.askopenfile()` at all, as it gives you no control over how the file is opened. Use `.askopenfilename()`, so you can call `open()` yourself, with `encoding=` or other parameters as needed. – jasonharper May 23 '20 at 03:41
  • What's a difference against hard-coded `filename`? Please share a [mcve]. – JosefZ May 30 '20 at 14:20

1 Answers1

0
from tkinter import filedialog

filename = filedialog.askopenfilename()
with open(filename, 'r', encoding='utf8') as file:
    textfromfile = file.read()
    file.close()
print(textfromfile)

The sample above pops up a filedialog, lets you choose a file, loads the file in reading modus, with utf-8 encoding, and prints it to the console.

I used this workaround with filedialog.askopenfilename() because the filedialog.askopenfile() method scrambled some of the characters in my textfiles ('ë' among others).

Now it works fine, since the original texts I use are all utf-8 encoded.