changing names of items in a list
Simon Brunning
simon at brunningonline.net
Wed Mar 19 10:46:56 EDT 2008
On Wed, Mar 19, 2008 at 2:21 PM, royG <roygeorget at gmail.com> wrote:
> hi
> i am trying to rename extension of files in a directory..as an initial
> step i made a method in
>
> class ConvertFiles:
> def __init__(self,infldr,outfldr):
> self.infldr=infldr
> self.outfldr=outfldr
> self.origlist=os.listdir(infldr)
> ....
> def renamefiles(self,extn):
> for x in self.origlist:
> x=x+"."+extn
>
> ...
>
> later when i print self.origlist i find that the elements of list are
> unchanged..even tho a print x inside the renamefiles() shows that
> extn is appended to x ..
> why does this happen?
Your 'x=' line is building a brand new string, and rebinding the name
'x' to it. It's not doing anything to the original list. See
<http://effbot.org/zone/python-objects.htm>.
I'd rewrite that as (untested):
def renamefiles(self, extn):
self.origlist = list((x + "." + extn) for x in self.origlist)
or
def renamefiles(self, extn):
self.origlist = list(("%s.%s" % (z, extn)) for x in self.origlist)
Better still, take a look at the os.path module...
--
Cheers,
Simon B.
simon at brunningonline.net
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues
More information about the Python-list
mailing list