python: question about files in Python.

Alex Martelli aleaxit at yahoo.com
Sun Feb 16 13:18:49 CET 2003


E.A. wrote:

> Hi there,
>    with the file object generated by file('some_file_name', 'w') is it
>    possible to get the file name from one of the file object's attributes?

Sure!  It's the kind of thing you can easily find on Python's docs,
OR by playing around in an interactive session -- let's try the
latter, as it's more fun...:

>>> f = file('some file name', 'w')
>>> dir(f)
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', 
'__init__', '__iter__', '__new__', '__reduce__', '__repr__', '__setattr__', 
'__str__', 'close', 'closed', 'fileno', 'flush', 'isatty', 'mode', 'name', 
'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 
'truncate', 'write', 'writelines', 'xreadlines']

Hmmm, that "name" thing looks interesting -- let's see:

>>> f.name
'some file name'
>>>


Oh well, so much for the fun -- it was clearly far too easy to find
this time, for it to be any fun at all.  Still, it IS a good approach
to keep in mind -- sometimes it's very fast, like here, other times
it can be quite a bit of fun.  Of course, Python's documentation and
the many excellent books about Python you can read (both paper and
on-line ones, both free and for-pay) offer an alternative, too, if
you LIKE reading the fine manuals.


Alex





More information about the Python-list mailing list