Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #73386

Re: Python Fails to Write to File

Date 2014-06-18 16:20 -0700
From Paul McNett <paul@mcnettware.com>
Subject Re: Python Fails to Write to File
References <8aaa4195-af5c-4ba3-a891-b1f268c086ac@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.11126.1403133632.18130.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Python Fails to Write to File cutey Love <cuteywithlove@gmail.com> - 2014-06-18 16:03 -0700
  Re: Python Fails to Write to File Ian Kelly <ian.g.kelly@gmail.com> - 2014-06-18 17:18 -0600
  Re: Python Fails to Write to File Paul McNett <paul@mcnettware.com> - 2014-06-18 16:20 -0700
  Re: Python Fails to Write to File cutey Love <cuteywithlove@gmail.com> - 2014-06-19 00:54 -0700
    Re: Python Fails to Write to File Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-06-19 09:39 +0100

csiph-web