简体   繁体   中英

I want tkinter asksaveasfile() to save as utf-8 in python. How can I solve it?

I wrote the following code in Python:

sveas = f.asksaveasfile()
sveas.write(f'{code.get(1.0,END)}')
sveas.close()

Here I want it to encode the file with utf-8. how can i solve

If you want to specify the encoding type, you need to pass encoding='utf-8' when you open the file. Since asksaveasfile() will open the file implicitly for you but you cannot specify the encoding type, so asksaveasfilename() need to be used instead and then you open the selected file using open() explicitly:

filename = f.asksaveasfilename()
with open(filename, 'w', encoding='utf-8') as fh:
    fh.write(code.get('1.0', END))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM