How to write the file I selected using filedialog.asksaveasfile?

I am trying to write the file that I just created using the filedialog.asksave file. I set the mode to "w". Should I open the file again or something else?

f = filedialog.asksaveasfile(mode='w', defaultextension=".csv")

keyList = []

for n in aDict.keys():
    keyList.append(n)

keyList = sorted(keyList, key=operator.itemgetter(0,1))
csvWriter = csv.writer(f)

for key in keyList:
    sal1 = aDict[(key[0],key[1])][0]
    sal2 = aDict[(key[0],key[1])][1]
    csvWriter.writerow(key[0], key[1], sal1, sal2)

f.close()
+4
source share
1 answer

You can simply use the writelink (type _io.TextIOWrapper) function returned by the function asksaveasfile.

for instance

from tkinter import filedialog, Tk

root = Tk().withdraw()

file = filedialog.asksaveasfile(mode='w', defaultextension=".csv")

if file:
    file.write("Hello World")
    file.close()

Note that the object returned by the function asksaveasfilehas the same type or class of the object that is returned by the built-in function open. Also note that the same function returns Noneif you click when a dialog box appears Cancel.

+4
source

All Articles