How To/python/MyMiscUtils/

Those are my exercises. Do not use them because this code is ugly and not working. If you want to work with paths using wildcards please use pythons glob module.

# -*- coding: utf-8 -*-
 
import os
import shutil
import re
import sys
 
class MSBatch:
 
    def __init__(self):
        self._statistics = []
 
    def _updateStats(self, stat):
        self._statistics.append(stat)
 
    def getStats(self):
        return self._statistics
 
    def printStats(self):
        for i in self._statistics:
            print i
 
    def clearStats(self):
        self._statistics = []
 
    def targetCompile(self, path, mask):
        if os.path.isdir(path):
            dir = path
            file = ''
        else:
            dir, file = os.path.split(path)
 
        if mask == '' or mask == '*' or mask == '*.*':
            return path
 
        while 1:
            if mask != mask.replace('**', '*'):
                mask = mask.replace('**', '*')
            else:
                break
 
        mask = mask.replace('*?', file[mask.find('*?'):], 1)
 
        fsb, fse = os.path.splitext(file)
        msb, mse = os.path.splitext(mask)
 
        file = ''.join([
            self._tcrec(fsb, msb),
            self._tcrec(fse, mse)
        ])
        #return '/'.join([dir, file])
        return file
    ###/targetMaskCompile
 
    def _tcrec(self, f, m, fi = 0, mi = 0, b = ''):
        if fi > len(f) - 1:
            if mi > len(m) - 1:
                return b
            else:
                if m[mi] != '?' and m[mi] != '*':
                    return self._tcrec(f, m, fi, mi + 1, b + m[mi])
                else:
                    return self._tcrec(f, m, fi, mi + 1, b)
        elif mi > len(m) - 1:
            return b
            #if name longer than mask, strip name
            '''if fi > len(f) - 1:
                return b
            else:
                return self._tcrec(f, m, fi + 1, mi, b + f[fi])'''
        else:
            if m[mi] == '?':
                return self._tcrec(f, m, fi + 1, mi + 1, b + f[fi])
            elif m[mi] == '*':
                if mi < len(m) - 1:
                    if m[mi + 1] == f[fi]:
                        return self._tcrec(f, m, fi, mi + 1, b)
                return self._tcrec(f, m, fi + 1, mi, b + f[fi])
            elif m[mi] == f[fi]:
                return self._tcrec(f, m, fi + 1, mi + 1, b + f[fi])
            else:
                return self._tcrec(f, m, fi + 1, mi + 1, b + m[mi])
    ###/_tcrec
 
    def _isInMask(self, filename, mask):
        tmp = mask.split('.')
        i = 0;
        while i < len(tmp):
            tmp[i] = re.escape(tmp[i])
            tmp[i] = tmp[i].replace('\*', '.*').replace('\?', '.')
            i += 1
        if re.compile('^' + ('\\.'.join(tmp)) + '$', re.I).match(filename) != None:
            return True
        else:
            return False
 
    def _createFilesList(self, path, mask):
        try:
            fileList = []
            for f in os.listdir(path):
                if not os.path.isdir(path + '/' + f):
                    if self._isInMask(f, mask):
                        fileList.append(f)
            return fileList
        except:
            self._updateStats('Cannot read dir.')
            return False
 
    def _createPathAndMask(self, path):
        path = os.path.normpath(path)
        path_mask = []
 
        if os.path.isdir(path):
            path_mask.append(path)
            path_mask.append('*')
        else:
            path_mask = os.path.split(path)
 
        return path_mask
    ###/_createPathAndMask
 
    def copy(self, files, target):
        fpath, fmask = self._createPathAndMask(files)
        tpath, tmask = self._createPathAndMask(target)
 
        if not os.path.isdir(fpath):
            self._updateStats('Source dir not exists!')
            return False
 
        c = 0
        for f in self._createFilesList(fpath, fmask):
            try:
                tmpf = os.path.normpath(fpath + '/' + f)
                tmpt = os.path.normpath(tpath + '/' + self.targetCompile(f, tmask))
                shutil.copy(tmpf, tmpt)
                self._updateStats(tmpf)
                c += 1
            except:
                self._updateStats('Cannot copy file ' + f)
        self._updateStats('%s file(s) copied!' % c)
 
    def delete(self, files):
        path_mask = self._createPathAndMask(files)
 
        if not os.path.isdir(path_mask[0]):
            self._updateStats('Source dir not exists!')
            return False
 
        c = 0
        for f in self._createFilesList(path_mask[0], path_mask[1]):
            try:
                tmpf = os.path.normpath(path_mask[0] + '/' + f)
                os.remove(tmpf)
                self._updateStats(tmpf)
                c += 1
            except:
                self._updateStats('Cannot copy file ' + f)
        self._updateStats('%s file(s) deleted!' % c)
    ###/delete
 
    def ren(self, files, target):
        fpath, fmask = self._createPathAndMask(files)
        tpath, tmask = self._createPathAndMask(target)
 
        if tpath != '':
            #ren cannot work in other dir than source
            self._updateStats('Ivalid syntax!')
            self._updateStats('%s file(s) renamed!' % 0)
            return False
 
        if not os.path.isdir(fpath):
            self._updateStats('Source dir not exists!')
            return False
        c = 0
        for f in self._createFilesList(fpath, fmask):
            try:
                tmpf = os.path.normpath(fpath + '/' + f)
                tmpt = os.path.normpath(fpath + '/' + self.targetCompile(f, tmask))
                os.rename(tmpf, tmpt)
                self._updateStats(tmpf)
                c += 1
            except:
                self._updateStats('Cannot rename file ' + f)
        self._updateStats('%s file(s) renamed!' % c)
    ###/ren
 
    def move(self, files, target):
        """move file(s)"""
        """i like the way dos move works so why reinvent wheel?"""
        try:
            os.system('move "%s" "%s"' % (
                os.path.normpath(files), os.path.normpath(target)
            ))
        except:
            print 'Cannot move file!'
 
    def md(self, path):
        print 'Use os.mkdir(path) instead'
        return False
 
    def rmdir(self):
        print 'Use os.rmdir(path) instead!'
        return False
 
 
if __name__ == "__main__":
    print """
dos = MSBatch()
dos.copy('tmp3/*.bak', 'tmp3/*.dat')
dos.delete('tmp2/*2*.*')
dos.ren('tmp3/Kopia (3) a.f', 'Ko*i4.mxt')
d.printStats()
"""