NoobyD
NoobyD

Reputation: 121

CSV write error in Python

I have the following code:

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)

When I run this I get:

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'>

I really am stuck as the other thread solutions don't work - what have I done wrong?

Thanks

Upvotes: 0

Views: 154

Answers (1)

Kevin
Kevin

Reputation: 76184

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

asksaveasfile returns a file object. You then try to call open on that file object. But open doesn't expect a file, it expects a file name.

Try using asksaveasfilename instead.

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)

Alternatively, continue to use asksaveasfile, but don't close the file, and don't try to open a new one.

def saveFile(self, master = None):
    f = asksaveasfile(mode='w',defaultextension='.csv')
    if not f:
        return
    w = csv.writer(f)
    w.writerow(globalCords)
    f.close()

Upvotes: 2

Related Questions