Python script for renaming and deleting files recursively (AKA: Fixing a broken magento update)

While updating a Magento (http://www.magentocommerce.com/) deployment, the updater failed after having successfully downloaded each new file, leaving hundreds of files in the form of:

.tmpWhateverFile.php <– looks like the new version of the file

WhateverFile.php.bak <– looks like the renamed version of the file queued for deletion

The following python script should help, it renames the .tmp version of the files to the original filename, and removes the .bak files.

import re, os

tmpfiles = “^\.tmp.*”
bakfiles = “^.+\.bak$”

def listFiles(dir):
basedir = dir
subdirlist = []
for fname in os.listdir(dir):
if os.path.isfile(os.path.join(basedir, fname)):
# search for tmp files and rename to good files
allowed_name = re.compile(tmpfiles).match
if allowed_name(fname):
newname = fname[4:]
os.rename(os.path.join(basedir, fname), os.path.join(basedir, newname))
print fname, “renamed to: “, newname

allowed_name = re.compile(bakfiles).match
if allowed_name(fname):
print “removing file: “, fname
os.remove(os.path.join(basedir, fname))
else:
subdirlist.append(os.path.join(basedir, fname))

for subdir in subdirlist:
listFiles(subdir)

listFiles(”d:\\test-dir\\code”)

Enjoy,

-AV

 
  • © 2009 penetrationtests.com