Reputation: 381
I am trying to write to a file that I just created using the filedialog.asksaveasfile. I set the mode to 'w'. Do I have to open the file again or something?
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()
Upvotes: 5
Views: 5787
Reputation: 15837
You can simply use the write
function of the reference (of type _io.TextIOWrapper
) returned by the asksaveasfile
function.
For example
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 asksaveasfile
function is of the same type or class of the object returned by the built-in open
function. Note also that the same function returns None
, if Cancel
is pressed when the dialog pops up.
Upvotes: 6