[Tutor] how to alter list content

Brett Hoerner bretthoerner at gmail.com
Thu Oct 13 23:50:54 CEST 2005


> i create a list of all JPG files with:
> >>> list = glob.glob('*.JPG')
> the content of 'list' is now:
> >>> print list
> ['DSC00001.JPG', 'DSC00002.JPG', 'DSC00003.JPG']
>
> but what i want is this type of list:
> ['DSC00001', 'DSC00002', 'DSC00003']

I would make use of os.path.splitext, which returns a tuple, where [0]
is the path and filename, and [1] is the extension.

In [1]: import os
In [2]: mylist = ['DSC00001.JPG', 'DSC00002.JPG', 'DSC00003.JPG']
In [3]: newlist = list()
In [4]: for x in mylist:
   ....:     newlist.append(os.path.splitext(x)[0])
In [5]: newlist
Out[6]: ['DSC00001', 'DSC00002', 'DSC00003']

Also, don't assign things to list, list() is a buildin function in
Python, you don't want to say list = x, because then you can't get to
the buitin list().

Brett


More information about the Tutor mailing list