[Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate

Alan Gauld alan.gauld at btinternet.com
Sun Feb 15 15:48:02 CET 2009


"Wayne Watson" <sierra_mtnview at sbcglobal.net> wrote

> Three questions about askopenfilename and enumerate.
>
> For askopenfilename:
> 1. Do I have to close the file before exiting from it?
> 2. How do I read each line of text in the file and quit when an eof 
> is reached?

This has nothing to do with askopenfilename!

Askopenfilename is the GUI equivalent of doing

fname = raw_input("What f8ile d9o you want to open?")

It simply returns a string which is a file name.
It does NOT open the file, process the file or do anything else.
It just returns the name as a string.

So for your questions:
> 1. Do I have to close the file before exiting from it?

Yes, it is good practice, but you need to open it first.

> 2. How do I read each line of text in the file and quit when an eof 
> is reached?

for line in open(fname):
     # process line

> This certainly doesn't do it.
>
>    def OpenConfigFile(self):
>
>        config_file = askopenfilename( title="Open Configuration 
> File",
>                                    filetypes=CEN_FILE_TYPES )
>        print "cfile-------: ",config_file, type(config_file)
>        for it in config_file:

No, this will asign each letter in the filename to 'it'
You need to open(config-file)
Just as you would in any other non GUI program.

If you had used askopenfile then it would be different because
it does return an open file object, then your code would do what
you expect. But personally I prefer to open the file myself since
that keeps my code more independant of the GUI.

> I get a "'str' object has no attribute 'readline'" msg

Because you are processing the file name not the file.

> 3. Where can I find out more about enumerate, as used here:
>
>  input_file=open('Initial.sen','r')
>  for (line_cnt, each_line) in enumerate(input_file):

In the python documentation - try the search box on
the python site or just google for python enumerate.
The latter took me on the third link to:

http://python.active-venture.com/whatsnew/section-enumerate.html

Which is probably the simplest and shortest explanayin you will get!

> Documentation for enumerate seems scarce.

> BTW, is there a thorough document on the use of files in Python
out there somewhere?

There is a ton of it and every tutorial (including mine) will have
a section on handling files. The official tutorial has a fair bit on
it and the reference manual has a whole section.

A good place to start might be the Library Reference (the one
they suggest keeping under your pillow!)

http://docs.python.org/library/stdtypes.html#file-objects

HTH,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list