Python Fails to Write to File

Paul McNett paul at mcnettware.com
Wed Jun 18 19:20:23 EDT 2014


On 6/18/14, 4:03 PM, cutey Love wrote:
> I'm trying to write data to a text file
>
> But I'm getting the error:
>
> TypeError: invalid file: <_io.TextIOWrapper

Always better to err on posting too much context (the entire traceback) 
than too little.


> Code is
>
> def saveFile():
>      file_path = filedialog.asksaveasfile(mode='w', filetypes=[('text files', '.txt')], defaultextension=".txt")
>      fo = open(file_path, 'w')

I used Google (searched on "filedialog.asksaveasfile") to realize that 
you are likely using Tkinter. I then used Google to find out the API for 
filedialog.asksaveasfile() and I found that it returns the ALREADY OPEN 
FILE for you to write to, not the name of the file you are writing to.

Referring to that same documentation, I see there's another function you 
are probably more interested in: filedialog.asksaveasfilename(). Then, 
you can open the file, write to it, and close it and be in control of 
every step. Not sure which is preferable, though, as I have no (recent) 
Tkinter experience.


>
>      for e in myList:
>          fo.write(e)
>
>
>      fo.close()

You should use a context manager to open, write to, and close files. 
Such as:

with open(file_path, 'w') as fo:
     for e in myList:
         fo.write(e)

> The file is being created if not already present but no data is written

filedialog.asksaveasfile() was opening it for you. It was being closed 
automatically when file_path fell out of scope (after the exception 
caused by your fo = open(file_path, 'w') line.

My response was intended to help.
Paul




More information about the Python-list mailing list