How to open and read an unknown extension file

Steven Howe howe.steven at gmail.com
Thu Apr 8 12:39:23 EDT 2010


On 04/08/2010 08:57 AM, Chris Colbert wrote:
> On Thu, Apr 8, 2010 at 11:42 AM, Kushal Kumaran
> <kushal.kumaran+python at gmail.com>  wrote:
>    
>> On Thu, Apr 8, 2010 at 9:00 PM, varnikat t<varnikat22 at gmail.com>  wrote:
>>      
>>> I am trying to do this
>>> if os.path.exists("*.*.txt"):
>>>              file=open("*.*.txt")
>>>              self.text_view.get_buffer().set_text(file.read())
>>> else:
>>>              file=open("*.*.html")
>>>              self.text_view.get_buffer().set_text(file.read())
>>>
>>> It gives error *.*.txt not existing....There are two files in the folder
>>> testing.pnm.txt
>>> and testing.pnm.html
>>> How to make it open any name and extension file and read it?
>>>
>>>        
>> os.path.exists does not do pattern matching like that.  Take a look at
>> the glob module.
>>
>> --
>> regards,
>> kushal
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>>      
> In [4]: files = [f for f in os.listdir(os.getcwd()) if
> os.path.splitext(f)[-1]=='.txt']
>
> In [5]: files
> Out[5]:
> ['pip-log.txt',
>   'extended_abstract.txt',
>   'testlog.txt',
>   'pymazon_error_log.txt',
>   'hny.txt']
>    
seems like a lot of work

from glob import glob

mylist = glob( "*.txt" )
for item in mylist:
     print item




More information about the Python-list mailing list