[Tutor] Re: A simpler mousetrap
Jacob S.
keridee at jayco.net
Sat Dec 18 23:28:09 CET 2004
Also, just as interesting, yet probably less reliable:
a = list(a)
a[-3:] = 'bak'
a = "".join(a)
OR
a = a.rstrip('pct')
a = a+'bak'
OR
a = a.rstrip('pct')+'bak' ## Which is essentially the same thing
OR
a = a[:-3]+'bak'
ETC.
HTH,
Jacob
> x=os.path.splitext(a)[0]+'.bak'
>
> Ah, jolly good, looks a bit simpler. Thanks!
>
> Regards,
>
> Liam Clarke
>
> On Thu, 16 Dec 2004 09:44:03 +0100, Wolfram Kraus
> <kraus at hagen-partner.de> wrote:
> > Liam Clarke wrote:
> > > Hi all,
> > >
> > > I'm writing some code, and I want to take a given path + filename, and
> > > change the file extension to *.bak.
> > >
> > > In doing so, (entirely internal this function), I am assuming -
> > >
> > > That the file will always have an extension
> > > Thathe extension will vary
> > > But, it will follow the general DOS format of name.ext
> > >
> > > So, I came up with this -
> > >
> > > a="./tc/arc/gab.pct"
> > >
> > > x=a.replace(a[a.rfind('.'):len(a)],'.bak')
> > >
> > > x="./tc/arc/gab.bak"
> > >
> > > So, it works, but it feels a bit, well, hacky to me. Not nearly hacky
> > > as using an regex though ; )
> > >
> > > I thought about
> > >
> > > a="./tc/arc/gab.pct"
> > >
> > > aList=a.split('.')
> > > aList[-1]='bak'
> > > a=".".join(aList)
> > >
> > > but I'm wondering if there's a simpler way, as there usually seems to
> > > be, and it's always so obvious once I'm shown it, like 6 down - Six on
> > > vehicle live in the manse (VI + car). Obvious once you know.
> > >
> > > Regards,
> > >
> > > Liam Clarke
> >
> > Hey Liam!
> >
> > The os.path module is your friend, especially split and splitext:
> > http://docs.python.org/lib/module-os.path.html
> >
> > HTH,
> > Wolfram
> >
> > _______________________________________________
> > Tutor maillist - Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
> --
> 'There is only one basic human right, and that is to do as you damn well
please.
> And with it comes the only basic human duty, to take the consequences.
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
More information about the Tutor
mailing list