Reputation: 25418
def listFiles(dir):
rootdir = dir
for root, subFolders, files in os.walk(rootdir):
for file in files:
yield os.path.join(root,file)
return
for f in listFiles(target):
if pattern in f:
os.rename(f,f.replace(pattern,'REPLACED'))
I have a file such as:
"C:\Dir3.30\file_3.30.xml"
If I do
os.rename(f,f.replace(pattern,'REPLACED'))
both the occurances would be replaced. How can I make sure that just the file name is being replaced
I want:
"C:\Dir3.30\file_REPLACED.xml"
Upvotes: 0
Views: 50
Reputation: 1121316
Split the filename off with os.path.split()
, call str.replace()
on just the name, and re-join:
path, name = os.path.split(f)
os.rename(f, os.path.join(path, name.replace(pattern, 'REPLACED')))
Upvotes: 1