我有以下代码:
def saveFile(self, master = None):
f = asksaveasfile(mode='w',defaultextension='.csv')
if f is None: # asksaveasfile returns `None` if dialog closed with "cancel".
return
f.close()
cords2save = globalCords # coordinates from another csv file
csvOpen = open(f, 'w')
w = csv.writer(fp)
w.writerow(cords2save)
当我跑步时,我得到:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Jem\AppData\Local\Programs\Python\Python35- 32\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
File "C:\Users\Jem\Documents\bbk\1FINisd\LineSimplification.py", line 143, in saveFile
csvOpen = open(f, 'w')
TypeError: invalid file: <_io.TextIOWrapper name='C:/Users/Jem/Documents/bbk/1FINisd/ard.csv' mode='w' encoding='cp1252'>
我真的被卡住,因为其他线程解决方案不起作用 - 我做错了什么?
由于
答案 0 :(得分:2)
f = asksaveasfile(mode='w',defaultextension='.csv')
asksaveasfile
返回一个文件对象。然后尝试在该文件对象上调用open
。但open
并不期望文件,它需要文件名。
请尝试使用asksaveasfilename
。
def saveFile(self, master = None):
filename = asksaveasfilename(mode='w',defaultextension='.csv')
if not filename:
return
with open(filename, 'w') as file:
w = csv.writer(file)
w.writerow(globalCords)
或者,继续使用asksaveasfile
,但不要关闭该文件,也不要尝试打开新文件。
def saveFile(self, master = None):
f = asksaveasfile(mode='w',defaultextension='.csv')
if not f:
return
w = csv.writer(f)
w.writerow(globalCords)
f.close()