get a copy of a string leaving original intact
kevin.bell at slcgov.com
Fri Oct 21 17:24:45 CEST 2005
I ended up slicing my string into a new one, rather than trying to have
a copy of the string to alter in one case, or leave intact in another
Thanks for the pointer on concatenating paths!
From: python-list-bounces+kevin.bell=slcgov.com at python.org
[mailto:python-list-bounces+kevin.bell=slcgov.com at python.org] On Behalf
Of Fredrik Lundh
Sent: Friday, October 21, 2005 2:10 AM
To: python-list at python.org
Subject: Re: get a copy of a string leaving original intact
"Bell, Kevin" wrote:
> I'm having trouble with something that seems like it should be simple.
> I need to copy a file, say "abc-1.tif" to another directory, but if
> in there already, I need to transfer it named "abc-2.tif" but I'm
> about it all wrong.
> Here's what doesn't work: (I'll add the copy stuff from shutil after
> figuring out the basic string manipulation.)
define "doesn't work".
> import os
> source = r"C:\Source"
> target = r"P:\Target"
> files = os.listdir(source)
> for f in files:
> if os.path.isfile(target + "\\" + f): # if it already exists
> print f + " exists"
> s = f # i'd like a copy to
> s = s.replace("-1", "-2")
> print "Altered it to be " + s
> print source + "\\" + s, target + "\\" + s
did you mean
print source + "\\" + f, target + "\\" + s
> print f + " IS NOT THERE YET"
> print source + "\\" + f, target + "\\" + f # use the original
btw, note that
source + "\\" + f
is better written as
for f in os.listdir(source):
sourcefile = os.path.join(source, f)
targetfile = os.path.join(target, f)
targetfile = os.path.join(target, f.replace("-1", "-2"))
print "copy", sourcefile, "to", targetfile
More information about the Python-list